async

A Method declared with async (e.g. public async void MyFucntion(… )  will run asnychronously, which means execution of the Method calling it will continue before it is complete.  

Task

If you want to force it to be a waiting to complete use ‘Task’ as its return type (e.g. public async Task MyFucntion(… )  

If you don’t want to force a user to have to await, then don’t use ‘Task’.

await

To wait on an aync fucntion to complete when calling it use await (eg. MyVariable = await SomeMethod(… )

The catch – to use await the method calling it must be async!  

Asynchronous Gotchas in C#

https://www.infoq.com/news/2013/04/async-csharp-fsharp/

How do I wait for an async method call to complete, in a method that isn’t async itself?

You typically don’t!  Find a way round it either by not using await or by being able to make your method async itself. Its like this to try and force you to use threading properly, not to block the UI thread for instance, and to try and help you avoid lock up situations.

Example method which uses await calls

	private async void MyMethodName()
	{

Allowing await to be used on the method or to return a value with await

	private async Task MyMethodName()
	{

A value can be returned within the Task, so if you wanted to return an int:

	private async Task<int> MyMethodName()
	{
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *