Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling async method synchronously

People also ask

Can we use async method in synchronous?

async Main is now part of C# 7.2 and can be enabled in the projects advanced build settings. If you have a simple asynchronous method that doesn't need to synchronize back to its context, then you can use Task. WaitAndUnwrapException: var task = MyAsyncMethod();

How do you call asynchronous method from synchronous method in C?

Solution C In that case, you could start the async method on the thread pool: var task = Task. Run(async () => await MyAsyncMethod()); var result = task. WaitAndUnwrapException();

Can we call async method from same class?

self-invocation - calling the async method from within the same class. It won't work. Because in this case, although it creates a proxy, the call bypasses the proxy and directly call the method so that Thread will not be spawned.

What happens when you call async method?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.


You can access the Result property of the task, which will cause your thread to block until the result is available:

string code = GenerateCodeAsync().Result;

Note: In some cases, this might lead to a deadlock: Your call to Result blocks the main thread, thereby preventing the remainder of the async code to execute. You have the following options to make sure that this doesn't happen:

  • Add .ConfigureAwait(false) to your library method or

  • explicitly execute your async method in a thread pool thread and wait for it to finish:

      string code = Task.Run(() => GenerateCodeAsync).Result;
    

This does not mean that you should just mindlessly add .ConfigureAwait(false) after all your async calls! For a detailed analysis on why and when you should use .ConfigureAwait(false), see the following blog post:

  • .NET Blog: ConfigureAwait FAQ

You should get the awaiter (GetAwaiter()) and end the wait for the completion of the asynchronous task (GetResult()).

string code = GenerateCodeAsync().GetAwaiter().GetResult();

You should be able to get this done using delegates, lambda expression

private void button2_Click(object sender, EventArgs e)
    {

        label1.Text = "waiting....";

        Task<string> sCode = Task.Run(async () =>
        {
            string msg =await GenerateCodeAsync();
            return msg;
        });

        label1.Text += sCode.Result;

    }

    private Task<string> GenerateCodeAsync()
    {
        return Task.Run<string>(() => GenerateCode());
    }

    private string GenerateCode()
    {
        Thread.Sleep(2000);
        return "I m back" ;
    }

I need to call this method from a synchronously method.

It's possible with GenerateCodeAsync().Result or GenerateCodeAsync().Wait(), as the other answer suggests. This would block the current thread until GenerateCodeAsync has completed.

However, your question is tagged with asp.net, and you also left the comment:

I was hoping for a simpler solution, thinking that asp.net handled this much easier than writing so many lines of code

My point is, you should not be blocking on an asynchronous method in ASP.NET. This will reduce the scalability of your web app, and may create a deadlock (when an await continuation inside GenerateCodeAsync is posted to AspNetSynchronizationContext). Using Task.Run(...).Result to offload something to a pool thread and then block will hurt the scalability even more, as it incurs +1 more thread to process a given HTTP request.

ASP.NET has built-in support for asynchronous methods, either through asynchronous controllers (in ASP.NET MVC and Web API) or directly via AsyncManager and PageAsyncTask in classic ASP.NET. You should use it. For more details, check this answer.


Microsoft Identity has extension methods which call async methods synchronously. For example there is GenerateUserIdentityAsync() method and equal CreateIdentity()

If you look at UserManagerExtensions.CreateIdentity() it look like this:

 public static ClaimsIdentity CreateIdentity<TUser, TKey>(this UserManager<TUser, TKey> manager, TUser user,
        string authenticationType)
        where TKey : IEquatable<TKey>
        where TUser : class, IUser<TKey>
    {
        if (manager == null)
        {
            throw new ArgumentNullException("manager");
        }
        return AsyncHelper.RunSync(() => manager.CreateIdentityAsync(user, authenticationType));
    }

Now lets see what AsyncHelper.RunSync does

  public static TResult RunSync<TResult>(Func<Task<TResult>> func)
    {
        var cultureUi = CultureInfo.CurrentUICulture;
        var culture = CultureInfo.CurrentCulture;
        return _myTaskFactory.StartNew(() =>
        {
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = cultureUi;
            return func();
        }).Unwrap().GetAwaiter().GetResult();
    }

So, this is your wrapper for async method. And please don't read data from Result - it will potentially block your code in ASP.

There is another way - which is suspicious for me, but you can consider it too

  Result r = null;

            YourAsyncMethod()
                .ContinueWith(t =>
                {
                    r = t.Result;
                })
                .Wait();