如何同步运行异步任务<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
阿晨1998