BENBUN Coder
BENBUN Coder

Reputation: 4881

Not getting the hang of TASKs and WAIT in C#

I have a stack of calls to a web api that need to be called asynchronously. I have never used the aysnc.

I have created a simple test console program, along the lines of :

class Program
{
    static void Main(string[] args)
    {
        ClassOne xx = new ClassOne();
        var v1 = xx.DummyTask();
    }
}

With the class defined as :

namespace GHTest.classes
{
    public class ClassOne
    {
        GitHubClient client;

        public ClassOne()
        {
           client = new GitHubClient(new ProductHeaderValue("OMHSite"));
        }

        public async Task<string> DummyTask()
        {
            Task<Repository> task = client.Repository.Get("openEHR", "CKM-mirror");
            task.Wait();

            var myResult = task.Result;
            return myResult.FullName;
        }
    }
}

Visual Studio states I should use the "await" operator as currently this code will run synchronously. Where does the await operator go?

Furthermore if the following statement throws an exception, how do I catch that in the task

client.Repository.Get("openEHR", "CKM-mirror");

Upvotes: 0

Views: 131

Answers (1)

Guvante
Guvante

Reputation: 19203

task.Wait(); is redudant, the call to task.Result would wait implicitly.

Here is your method rewritten to use await.

Task<Repository> task = client.Repository.Get("openEHR", "CKM-mirror");
var myResult = await task;

return myResult.FullName;

You don't need .Result either as the type of await on a Task<T> is T.

On the subject of exception handling you will need to do a try/catch around the await (or Result in your original code). As that is when the exception will be rethrown. Note that this is only true if the exception is thrown in the Task, in theory the Get function itself could throw which would have to be caught there.

Also note that since you are returning an async you can choose to catch the exception wherever you await (or Result) the call.

Finally don't forget that if you don't await the result of DummyTask your task may not complete (or Result).

static void Main(string[] args)
{
    ClassOne xx = new ClassOne();
    var v1 = xx.DummyTask();
    var resultV1 = v1.Result; //Forces the execution of v1 by requesting its result.
}

Upvotes: 6

Related Questions