当在工作线程上调用的方法需要在UI线程上运行代码并在执行其他操作之前等待它完成时,可以这样做:
public int RunOnUi(Func<int> f)
{
int res = Application.Current.Dispatcher.Invoke(f);
return res;
}
但如果我想用任务做什么怎么办?有没有办法让RunOnUi方法创建一个在UI上启动并返回它的任务,以便调用者(在工作线程上运行)可以等待它?符合以下签名的东西:public Task<int> StartOnUi(Func<int> f)
?
一种方法如下:
public Task<int> RunOnUi(Func<int> f)
{
var task = new Task<int>(f);
task.Start(_scheduler);
return task;
}
此处,假设_schduler
拥有ui TaskScheduler
。但我对制作&#34; cold&#34;并不太舒服。任务并使用start方法运行它们。这是&#34;推荐&#34;方式还是有更优雅的方式去做?
答案 0 :(得分:6)
只需使用InvokeAsync
代替Invoke
,然后在函数返回的DispatcherOperation<int>
内返回Task<int>
。
//Coding conventions say async functions should end with the word Async.
public Task<int> RunOnUiAsync(Func<int> f)
{
var dispatcherOperation = Application.Current.Dispatcher.InvokeAsync(f);
return dispatcherOperation.Task;
}
如果您无法访问.NET 4.5,则会更复杂一些。您需要使用BeginInvoke
和TaskCompletionSource
来包裹BeginInvoke
返回的DispaterOperation
public Task<int> RunOnUi(Func<int> f)
{
var operation = Application.Current.Dispatcher.BeginInvoke(f);
var tcs = new TaskCompletionSource<int>();
operation.Aborted += (sender, args) => tcs.TrySetException(new SomeExecptionHere());
operation.Completed += (sender, args) => tcs.TrySetResult((int)operation.Result);
//The operation may have already finished and this check accounts for
//the race condition where neither of the events will ever be called
//because the events where raised before you subscribed.
var status = operation.Status;
if (status == DispatcherOperationStatus.Completed)
{
tcs.TrySetResult((int)operation.Result);
}
else if (status == DispatcherOperationStatus.Aborted)
{
tcs.TrySetException(new SomeExecptionHere());
}
return tcs.Task;
}