Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't await async extension method

Situation is pretty simple - I wrote an extension method and made it async with return type Task<T>. But when I try to call it using await, compiler throws an error which suggests that the extension method wasn't recognized as async at all. Here's my code:

public static async Task<NodeReference<T>> CreateWithLabel<T>(this GraphClient client, T source, String label) where T: class
    {
        var node = client.Create(source);
        var url = string.Format(ConfigurationManager.AppSettings[configKey] + "/node/{0}/labels", node.Id);
        var serializedLabel = string.Empty;
        using (var tempStream = new MemoryStream())
        {
            new DataContractJsonSerializer(label.GetType()).WriteObject(tempStream, label);
            serializedLabel = Encoding.Default.GetString(tempStream.ToArray());
        }
        var bytes = Encoding.Default.GetBytes(serializedLabel);

        using (var webClient = new WebClient())
        {
            webClient.Headers.Add("Content-Type", "application/json");
            webClient.Headers.Add("Accept", "application/json; charset=UTF-8");
            await webClient.UploadDataTaskAsync(url, "POST", bytes);
        }

        return node;
    }


var newNode = await client.CreateWithLabel(new Task(), "Task");

Exact error message is this:

The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'

Am I doing something wrong or is it a language/compiler limitation?

like image 404
chester89 Avatar asked Nov 01 '13 13:11

chester89


Video Answer


1 Answers

The error message is pretty clear: the method where you're calling the extension method should be marked as async.

public Task<string> MyExtension(this string s) { ... }

public async Task MyCallingMethod()
{    
    string result = await "hi".MyExtension();
}

Re-reading this part should make much more sense now:

"The 'await' operator can only be used within an async method. "

like image 138
dcastro Avatar answered Oct 22 '22 12:10

dcastro