Mic*_*ana 72 c# wpf multithreading thread-safety task-parallel-library
使用Thread非常简单
Thread thread = new Thread(MethodWhichRequiresSTA);
thread.SetApartmentState(ApartmentState.STA);
Run Code Online (Sandbox Code Playgroud)
如何使用WPF应用程序中的任务完成相同的操作?这是一些代码:
Task.Factory.StartNew
(
() =>
{return "some Text";}
)
.ContinueWith(r => AddControlsToGrid(r.Result));
Run Code Online (Sandbox Code Playgroud)
我收到了一个InvalidOperationException
调用线程必须是STA,因为许多UI组件都需要这个.
dtb*_*dtb 72
您可以使用TaskScheduler.FromCurrentSynchronizationContext方法获取当前同步上下文的TaskScheduler(当您运行WPF应用程序时,它是WPF调度程序).
然后使用接受TaskScheduler 的ContinueWith重载:
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(...)
.ContinueWith(r => AddControlsToGrid(r.Result), scheduler);
Run Code Online (Sandbox Code Playgroud)