Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. "


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...