如何同步运行异步任务<T>方法?我正在学习异步/等待,并遇到需要同步调用异步方法的情况。我怎么能这么做?异步方法:public async Task<Customers> GetCustomers(){
return await Service.GetCustomersAsync();}正常使用:public async void GetCustomers(){
customerList = await GetCustomers();}我尝试使用以下方法:Task<Customer> task = GetCustomers();task.Wait()Task<Customer> task = GetCustomers();task.RunSynchronously();
Task<Customer> task = GetCustomers();while(task.Status != TaskStatus.RanToCompletion)我还从这里但是,当调度程序处于挂起状态时,它无法工作。public static void WaitWithPumping(this Task task) {
if (task == null) throw new ArgumentNullException(“task”);
var nestedFrame = new DispatcherFrame();
task.ContinueWith(_ => nestedFrame.Continue = false);
Dispatcher.PushFrame(nestedFrame);
task.Wait();}下面是调用的异常和堆栈跟踪RunSynchronously:System.InvalidOperationException讯息:对于未绑定到委托的任务,可能不会同步调用。InnerException*空来源*姆斯科利布斯塔克迹: at System.Threading.Tasks.Task.InternalRunSynchronously(TaskScheduler scheduler)
at System.Threading.Tasks.Task.RunSynchronously()
at MyApplication.CustomControls.Controls.MyCustomControl.CreateAvailablePanelList() in C:\Documents and Settings\..
.\MyApplication.CustomControls\Controls\MyCustomControl.xaml.cs:line 638
at MyApplication.CustomControls.Controls.MyCustomControl.get_AvailablePanels() in C:\Documents and Settings\.
..\MyApplication.CustomControls\Controls\MyCustomControl.xaml.cs:line 233
at MyApplication.CustomControls.Controls.MyCustomControl.<CreateOpenPanelList>b__36(DesktopPanel panel) in C
:\Documents and Settings\...\MyApplication.CustomControls\Controls\MyCustomControl.xaml.cs:line 597
at System.Collections.Generic.List`1.ForEach(Action`1 action)
at MyApplication.CustomControls.Controls.MyCustomControl.<CreateOpenPanelList>d__3b.MoveNext() in C:\Documents and Settings
\...\MyApplication.CustomControls\Controls\MyCustomControl.xaml.cs:line 625
3 回答
阿晨1998
TA贡献2037条经验 获得超6个赞
建议async-await
.净4.5
// For Task<T>: will block until the task is completed...var result = task.Result; // For Task (not Task<T>): will block until the task is completed...task2.RunSynchronously();
.net 4.0
var x = (IAsyncResult)task;task.Start();x.AsyncWaitHandle.WaitOne();
task.Start();task.Wait();
- 3 回答
- 0 关注
- 873 浏览
添加回答
举报
0/150
提交
取消