【发布时间】:2013-11-12 17:15:14
【问题描述】:
情况很简单——我写了一个扩展方法并使它与返回类型Task<T>异步。但是当我尝试使用 await 调用它时,编译器会抛出一个错误,表明扩展方法根本没有被识别为异步。
这是我的代码:
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");
确切的错误信息是这样的:
“await”运算符只能在异步方法中使用。考虑使用 'async' 修饰符标记此方法并将其返回类型更改为 'Task'
我做错了什么还是语言/编译器限制?
【问题讨论】:
-
请贴出代码。
-
提示:如果您关注TAP conventions,其他开发人员将更容易使用您的
async方法。
标签: c# .net extension-methods async-await c#-5.0