Consider this code on a console application written with vs 2015:
using System; using System.Threading.Tasks; public class Example { public static void Main() { Console.WriteLine("Wait please...."); DateTime time1 = DateTime.Now; Task task1 = MyAsyncFun1(); Task task2 = MyAsyncFun2(); task1.Wait(); task2.Wait(); DateTime time2 = DateTime.Now; Console.WriteLine("time elapsed: " + (time2 - time1).TotalSeconds); Console.ReadLine(); } private static async Task MyAsyncFun1() { await Task.Yield(); System.Threading.Thread.Sleep(2000); } private static async Task MyAsyncFun2() { await Task.Yield(); System.Threading.Thread.Sleep(2000); } } There are two methods called asynchronously and all work fine, the 'time elapsed' does not exceeded 2 seconds becouse the execution is parallel.
But when i wrote this code inside an acion method of an ApiController like this:
public class MyController : ApiController { private static async Task MyAsyncFun1() { await Task.Yield(); System.Threading.Thread.Sleep(2000); } private static async Task MyAsyncFun2() { await Task.Yield(); System.Threading.Thread.Sleep(2000); } public async Task<ApiResult> MyAction([FromBody] Mymodel model) { DateTime time1 = DateTime.Now; Task task1 = MyAsyncFun1(); Task task2 = MyAsyncFun2(); task1.Wait(); task2.Wait(); DateTime time2 = DateTime.Now; double d=(time2 - time1).TotalSeconds; return .....; } } the execution hang indefinitely on the task1.Wait() statement.
Wait()when you canawaitin an async method?.Wait()on anasync Taskmethod