c# extension – AwaitResult

The Problem

When using async coding there are various places where you cannot use the await operator, e.g. static main in a console app.

You need to add code to force the async method to be synchronous

_service.DoSomethingAsync().GetAwaiter().GetResult(); 

I found myself having to do this a few times in my code, so thought I should create an extension to simplify this..

The solution

Create a class “TaskExtension.cs”, and add the following code

public static class TaskExtension
{
	public static T AwaitResult(this System.Threading.Tasks.Task task)
	{
	  return task.GetAwaiter().GetResult();
	}
}

Example

This is how you can use it..

_service.DoSomethingAsync().AwaitResult();

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.