SynchronizationContext.Current
.NET 4.0 的主线程上意外为 null的问题的解决方法是什么?看:
问问题
692 次
1 回答
4
我创建了几个匹配的扩展方法,ContinueWith
除了StartNew
它们还需要一个额外的SyncronizationContext
. SynchronizationContext
然后,我使用此参数在执行操作之前恢复预期:
下面,我给出了例子:
public static class TaskExtensionMethods
{
public static Task ContinueWith_UsingSyncContextWorkaround(this Task task, Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler, SynchronizationContext sc)
{
Action<Task> actionWithWorkaround = t =>
{
SynchronizationContext.SetSynchronizationContext(sc);
continuationAction(t);
};
return task.ContinueWith(actionWithWorkaround, cancellationToken, continuationOptions, scheduler);
}
public static Task StartNew_UsingSyncContextWorkaround(this TaskFactory taskFactory, Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler, SynchronizationContext sc)
{
Action actionWithWorkaround = () =>
{
SynchronizationContext.SetSynchronizationContext(sc);
action();
};
return taskFactory.StartNew(actionWithWorkaround, cancellationToken, creationOptions, scheduler);
}
}
然后我使用这些扩展方法代替.ContinueWith
or.StartNew
相关问题:
于 2014-01-06T15:29:44.423 回答