.NET 4.0中SynchronizationContext.Current为null的问题的解决方法 [英] Workaround for issue in .NET 4.0 where SynchronizationContext.Current is null
问题描述
.NET 4.0主线程上 SynchronizationContext.Current
意外为空的问题的解决方法是什么?请参阅:
What is a workaround for the issue where the SynchronizationContext.Current
is null unexpectedly on the main thread in .NET 4.0? See:
- SynchronizationContext.Current is null in Continuation on the main UI thread
推荐答案
我创建了几种扩展方法,它们与 ContinueWith
和 StartNew $ c相匹配$ c>,除了它们还需要另外的
SyncronizationContext
。然后,在执行操作之前,我使用此参数恢复预期的 SynchronizationContext
:
I created several extension methods that matched ContinueWith
and StartNew
except that they also take an additional SyncronizationContext
. I then use this argument to restore the expected SynchronizationContext
before executing the action:
下面,我给出了示例:
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
I then use these extension methods in place of .ContinueWith
or .StartNew
相关问题:
- How to create a generic Task.ContinueWith extension method
这篇关于.NET 4.0中SynchronizationContext.Current为null的问题的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!