4

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

4

1 回答 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);
    }
}

然后我使用这些扩展方法代替.ContinueWithor.StartNew

相关问题:

于 2014-01-06T15:29:44.423 回答