반응형
UI 스레드에서 작업 계속
작업 계속을 초기 작업이 생성된 스레드에서 실행하도록 지정할 수 있는 '표준' 방법이 있습니까?
현재 아래의 코드를 가지고 있습니다.이것은 동작하고 있습니다만, 디스패처를 추적해, 제2의 액션을 작성하는 것은 불필요한 오버헤드로 생각됩니다.
dispatcher = Dispatcher.CurrentDispatcher;
Task task = Task.Factory.StartNew(() =>
{
DoLongRunningWork();
});
Task UITask= task.ContinueWith(() =>
{
dispatcher.Invoke(new Action(() =>
{
this.TextBlock1.Text = "Complete";
}
});
의 계속을 호출합니다.TaskScheduler.FromCurrentSynchronizationContext()
:
Task UITask= task.ContinueWith(() =>
{
this.TextBlock1.Text = "Complete";
}, TaskScheduler.FromCurrentSynchronizationContext());
현재 실행 컨텍스트가 UI 스레드에 있는 경우에만 적합합니다.
비동기에서는 다음 작업을 수행합니다.
await Task.Run(() => do some stuff);
// continue doing stuff on the same context as before.
// while it is the default it is nice to be explicit about it with:
await Task.Run(() => do some stuff).ConfigureAwait(true);
단,
await Task.Run(() => do some stuff).ConfigureAwait(false);
// continue doing stuff on the same thread as the task finished on.
UI로 전송해야 하는 반환 값이 있는 경우 다음과 같이 일반 버전을 사용할 수 있습니다.
이 경우는 MVVM View Model에서 호출됩니다.
var updateManifest = Task<ShippingManifest>.Run(() =>
{
Thread.Sleep(5000); // prove it's really working!
// GenerateManifest calls service and returns 'ShippingManifest' object
return GenerateManifest();
})
.ContinueWith(manifest =>
{
// MVVM property
this.ShippingManifest = manifest.Result;
// or if you are not using MVVM...
// txtShippingManifest.Text = manifest.Result.ToString();
System.Diagnostics.Debug.WriteLine("UI manifest updated - " + DateTime.Now);
}, TaskScheduler.FromCurrentSynchronizationContext());
이 버전은 매우 유용한 스레드이며 매우 간단한 구현이라고 생각하기 때문에 추가하려고 합니다.멀티스레드 어플리케이션의 경우 다양한 타입으로 여러 번 사용하고 있습니다.
Task.Factory.StartNew(() =>
{
DoLongRunningWork();
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{ txt.Text = "Complete"; }));
});
작업 중에 UI 스레드로 작업을 수행할 수 있는 좋은 방법을 찾고 있었기 때문에 구글을 통해 이곳에 왔습니다.호출 실행 - 다음 코드를 사용하여 사용할 수 있습니다.await
UI 스레드로 다시 돌아가려면 을 클릭하십시오.
이게 도움이 됐으면 좋겠어요.
public static class UI
{
public static DispatcherAwaiter Thread => new DispatcherAwaiter();
}
public struct DispatcherAwaiter : INotifyCompletion
{
public bool IsCompleted => Application.Current.Dispatcher.CheckAccess();
public void OnCompleted(Action continuation) => Application.Current.Dispatcher.Invoke(continuation);
public void GetResult() { }
public DispatcherAwaiter GetAwaiter()
{
return this;
}
}
사용방법:
... code which is executed on the background thread...
await UI.Thread;
... code which will be run in the application dispatcher (ui thread) ...
언급URL : https://stackoverflow.com/questions/4331262/task-continuation-on-ui-thread
반응형
'programing' 카테고리의 다른 글
Relay Command가 필요한 이유 (0) | 2023.04.11 |
---|---|
WPF List View 항목을 가로 스크롤 막대처럼 가로로 반복하려면 어떻게 해야 합니까? (0) | 2023.04.11 |
이 경우 실제 폭과 실제 높이가 0.0인 이유는 무엇입니까? (0) | 2023.04.11 |
Swift에서 수학적인 PI 상수를 얻는 방법 (0) | 2023.04.11 |
SQL Azure 데이터베이스를 로컬 개발 서버에 복사하려면 어떻게 해야 합니까? (0) | 2023.04.06 |