在.NET 4.0的主线程上SynchronizationContext.Current
意外为空的问题是什么解决方法?见:
答案 0 :(得分: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
或.StartNew
相关问题: