如何同步運(yùn)行異步任務(wù)<T>方法?我正在學(xué)習(xí)異步/等待,并遇到需要同步調(diào)用異步方法的情況。我怎么能這么做?異步方法: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)我還從這里但是,當(dāng)調(diào)度程序處于掛起狀態(tài)時(shí),它無法工作。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();}下面是調(diào)用的異常和堆棧跟蹤RunSynchronously:System.InvalidOperationException訊息:對于未綁定到委托的任務(wù),可能不會同步調(diào)用。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貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超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 關(guān)注
- 921 瀏覽
添加回答
舉報(bào)
0/150
提交
取消