Understanding async and await, Task.WaitAll, Task.Run, and parallelism: part 2 - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Tuesday, August 7, 2018

Understanding async and await, Task.WaitAll, Task.Run, and parallelism: part 2

So another issue with async, await came up. I was using Task.WaitAll to make it parallel, but it wasn't parallel. var task1 = Method1(); var task2 = Method2(); Task.WhenAll(task1, task2) Now Method1() and Method2() had some code that took some time. Now my code was making some large web service calls, but we can demonstrate this more easily just by sleeping for 10 seconds. public async Task Method1() { Thread.Sleep(10000); // Ten seconds } public async Task Method2() { await Task.Delay(10000); // 10 second task } I expected these to run in parallel, but they didn't. Let me explain why. When calling a method that returns task, it doesn't actually return until the first await. Notice Method1() doesn't have an await. So Method1() will run synchronously until the first await. Method2(), however, is pretty much the same, but does have an await. So it returns immediately. Getting parallelism is easy. Wrap the method in Task.Run(). public async Task Method1() { Task.Run(Thread.Sleep, 10000));...


I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too.

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.


This article is related to

Development

No comments:

Post a Comment