I'm looking for a simple C# example of a pattern that meets the following requirements:
- I want to execute 2 methods asynchronously, initiating the second without waiting for the first to finish.
- Each method accepts a parameter and returns and output value.
- I then want to wait for the results of both before moving on.
This seemed like a scenario where I could easily use the async and await keywords but after looking at a couple of Hello World examples, I was surprised that I could not easily meet all of the above criteria at the same time. For example, while using the await keyword kept my UI from being non blocking and allowing my app to continue to be responsive to events while I await the completion of a method, the methods were still executing synchronously. Or if I was able to execute asynchronously, I had trouble trying to pass an input parameter to the calling method and receiving a result back.
The following seems to meet my requirements and leads me to believe that I'd be able to make great use out of it but first I'd like to get your feedback on how it can be improved.
I've played around with Threads before and found that make my code much more complex and was expecting that the "async and await" keywords would make my life easier but the following code which appears to meet my requirements does not even use these keywords. Am I using the "Parallel Task Library" here? If so, how would you contrast the functionality in this library to the async and await functionality?
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ASyncCourse
{
static class Program
{
static void Main()
{
int result1 = 0;
int result2 = 0;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Task task1 = Task.Run(() => result1 = DoSomeWork(1));
Debug.WriteLine($"After Task1: {stopWatch.Elapsed}");
Task task2 = Task.Run(() => result2 = DoSomeOtherWork(10));
Debug.WriteLine($"After Task2: {stopWatch.Elapsed}");
Task.WaitAll(task1, task2);
stopWatch.Stop();
int sum;
sum = result1 + result2;
Debug.WriteLine($"Sum: {sum}");
Debug.WriteLine($"Final: {stopWatch.Elapsed}");
}
private static int DoSomeOtherWork(int waitFor)
{
Thread.Sleep(waitFor * 1000);
return waitFor;
}
private static int DoSomeWork(int waitFor)
{
Thread.Sleep(waitFor * 1000);
return waitFor;
}
}
}