Recent Entries 2
- pattern critical 112d agoUsing async/await for multiple tasksI'm using an API client that is completely asynchrounous, that is, each operation either returns `Task` or `Task`, e.g: ``` static async Task DoSomething(int siteId, int postId, IBlogClient client) { await client.DeletePost(siteId, postId); // call API client Console.WriteLine("Deleted post {0}.", siteId); } ``` Using the C# 5 async/await operators, what is the correct/most efficient way to start multiple tasks and wait for them all to complete: ``` int[] ids = new[] { 1, 2, 3, 4, 5 }; Parallel.ForEach(ids, i => DoSomething(1, i, blogClient).Wait()); ``` or: ``` int[] ids = new[] { 1, 2, 3, 4, 5 }; Task.WaitAll(ids.Select(i => DoSomething(1, i, blogClient)).ToArray()); ``` Since the API client is using HttpClient internally, I would expect this to issue 5 HTTP requests immediately, writing to the console as each one completes.
- pattern critical 112d agoHow would I run an async Task<T> method synchronously?I am learning about async/await, and ran into a situation where I need to call an async method synchronously. How can I do that? Async method: ``` public async Task GetCustomers() { return await Service.GetCustomersAsync(); } ``` Normal usage: ``` public async void GetCustomers() { customerList = await GetCustomers(); } ``` I've tried using the following: ``` Task task = GetCustomers(); task.Wait() Task task = GetCustomers(); task.RunSynchronously(); Task task = GetCustomers(); while(task.Status != TaskStatus.RanToCompletion) ``` I also tried a suggestion from here, however it doesn't work when the dispatcher is in a suspended state. ``` 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(); } ``` Here is the exception and stack trace from calling `RunSynchronously`: System.InvalidOperationException Message: RunSynchronously may not be called on a task unbound to a delegate. InnerException: null Source: mscorlib StackTrace: ``` 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.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.Custom