【发布时间】:2016-06-16 22:54:08
【问题描述】:
我和this person had有同样的问题。然而问题是使用 .Net 4.5 回答的,但我只有 .Net 4.0。
因此,我基于this tutorial 创建了自己的异步信号量,并根据发布答案的人的其他 cmets 实现了我的代码:
private void Foo()
{
try
{
Semaphore.WaitAsync().ContinueWith(previousTask =>
{
if (Dispatcher.FromThread(Thread.CurrentThread) != null)
{
Bar();
}
else
{
Application.Current.Dispatcher.Invoke(new Action(() => Bar()));
}
});
}
finally
{
Semaphore.Release();
}
}
但这对我不起作用,Bar 是并行调用的。
【问题讨论】:
-
您在异步发生之前释放信号量。您应该使用
await而不是所有这些。 -
@SLaks:我没有 .Net 4.5。
-
然后使用 Microsoft.Bcl.Async。
-
只需将 Release() 调用移到 Bar() 调用之后。 lambda 表达式并非总是是正确的选择,通过将延续代码移动到单独的方法中更容易解决这个问题。
标签: c# wpf multithreading ui-thread