Foo
Foo

Reputation: 4606

How to make this code use async and await?

I am just begining to learn async and await. How do I make this code below work with async/await? It compiles only if I remove the await keyword.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            AsyncExperiment();
            Console.ReadLine();
        }

        private static void AsyncExperiment()
        {
              //var t1 =  Task.Run(() => LongProcess()); //ok
              var t2= await  Task.Run(()=>LongProcess()); //compile time error

        }


        private static void LongProcess()
        {
            //a call to some slow service
        }

    }
}

Upvotes: 0

Views: 122

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149598

Other than LongProcess being void, the await keyword is missing the async keyword which needs to come in the method signature:

private static async void AsyncExperiment()

A couple of things to note:

  1. async void is ment only for top level event handlers. Instead, use async Task when you have a void returning method

  2. Should I expose asynchronous wrappers for synchronous methods?, The answer is usually no. You should think about why you need to wrap this method in a Task.Run. I know this is an attempt to test the Task Parallel Library, but you should keep that in mind. Let the consumer of your synchronous method use Task.Run instead.

  3. If your work is IO bound, like calling a web service, there is usually no need to use a ThreadPool thread. For example, if your service is using REST, you can use the HttpClient library which exposes asynchronous methods (GetAsync, PostAsync, etc..). With async, really, There Is No Thread.

Upvotes: 4

Jeff Mercado
Jeff Mercado

Reputation: 134571

LongProcess() is a method that returns void.

Just like you can't expect this to work:

var result = LongProcess();

You cannot expect this to work:

var result = await Task.Run(() => LongProcess());

Task.Run() as used here returns a Task (that has no result). Just call it without assigning to anything.

await Task.Run(() => LongProcess());

Upvotes: 3

Related Questions