It's possible to do asynchronous programming in C#. In order to ease your life a little bit they came up with the idea to add a couple of extra keywords: async and await.
using System;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
int result = DoSomeJobAsync().Result;
Console.WriteLine("Result: " + result);
}
async static Task<int> DoSomeJobAsync() {
return await Task.Run(() => { return 777; });
}
}
}
So, to tell compiler you want your method to be "asynchronous" you have to prepend it with async keyword which enables you to use await keyword inside it in order to create so-called suspension point which is basically the asynchronous equivalent of blocking. The whole concept is meant to manage asynchronous and synchronous calls separately, but I'll tell you what, it's impossible and if you disagree, take a look at what happens in Main. As we cannot use await in synchronous method we are forced to block until we get the result from asynchronous chain of methods.
No comments:
Post a Comment