我处理此问题的方法是将 UI 线程传递TaskScheduler
到将在后台线程上运行的对象中。然后,每当后台线程需要在 UI 线程上发生某些事情时,我都会使用Task.Factory.StartNew()
我TaskScheduler
提供给对象的 。为了显示:
using System.Threading.Tasks;
public class BackgroundThread {
IView _view;
TaskScheduler _uiThreadScheduler;
// This object is constructed on the main thread. The main thread's TaskScheduler
// can be acquired with TaskScheduler.FromCurrentSynchronizationContext()
public BackgroundThread(IView view, TaskScheduler uiThreadScheduler){
this._view = view;
this._uiThreadScheduler = uiThreadScheduler;
}
public void DoWork(){
// Code in this function executes on a background thread
//...
string filename;
var task = Task.Factory.StartNew(() =>
{
filename = _view.GetSaveFilename();
}, CancellationToken.None, TaskCreationOptions.None, _uiThreadScheduler);
task.Wait();
// filename now has input from the user, or is null
}
}
通过将 UI 的实现隐藏在IView
接口后面,后台线程不依赖于任何特定的 UI 实现。