解决.NET 4.0中SynchronizationContext.Current为空的问题

时间:2014-01-06 15:29:44

标签: c# winforms task-parallel-library synchronizationcontext

在.NET 4.0的主线程上SynchronizationContext.Current意外为空的问题是什么解决方法?见:

1 个答案:

答案 0 :(得分:4)

我创建了几个与ContinueWithStartNew匹配的扩展方法,只是它们还需要额外的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

相关问题: