Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

Generic Methods for async await in a class Library

Is it possible to write generic async methods in a Dot Net 4.0 class Library?

Reason for asking this
Because then I will be able to use this dll in any project that targets .Net 4.0. Even use in IDE's like VS 2010 which do not support await and async keywords.

Problem
My problem is that my main app code is in .Net 4.0 and I use VS 2010. I was thinking that I will use VS 2012 to create a generic dll which I can reference in my main code and use it.

In my app there are some code that takes time and is fires in UI Thread, causing my app to hang. If I can achieve what I want, then those synchronous calls will not hang UI.

Something like this

public static class AsyncHelpers
{
    public static async Task<T> RunMethodAsync<T>()
    {
        //What to do here?
    }
}

Upvotes: 0

Views: 1691

Answers (2)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

I did it. Here's what I did.

If you use .Net 4.0 using Nuget Package Manager Console, install Microsoft BCL Async. Then use this code

using System.Threading.Tasks;

namespace AsyncAwaitCL
{
    public class AsyncHelpers
    {
        public static async Task<T> RunMethodAsync<T>(Task<T> task)
        {
            T returnValue = default(T);
            returnValue = await task;
            return returnValue;
        }
    }
}

and you are done.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292725

You can use async/await in a project that targets .NET 4.0; you just need to reference the Microsoft.Bcl.Async NuGet package, which provides the necessary types. And of course you also need the C# 5 (or higher) compiler, which means VS2012 or more recent.

Upvotes: 1

Related Questions