C# 从 Task.Run 获取返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18050836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting return value from Task.Run
提问by Null Reference
I have the following code:
我有以下代码:
public static async Task<string> Start(IProgress<ProcessTaskAsyncExProgress> progress)
{
const int total = 10;
for (var i = 0; i <= total; i++)
{
await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));
if (progress != null)
{
var args = new ProcessTaskAsyncExProgress
{
ProgressPercentage = (int)(i / (double)total * 100.0),
Text = "processing " + i
};
progress.Report(args);
}
}
return "Done";
}
private static string RunLongTask(string taskName)
{
Task.Delay(300);
return taskName + "Completed!";
}
How do I get back the string value of RunLongTaskfrom this line: await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));?
我如何RunLongTask从这一行取回字符串值:await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));?
I've tried:
我试过了:
var val = await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture))).Result;
But I get an error saying "string is not awaitable".
但是我收到一条错误消息,说“字符串不可等待”。
采纳答案by Haris Hasan
Remove the Resultfrom the end. When you awaityou will get the Resultback from the await-able method.
Result从末尾删除。当您从 await-able 方法中await获得Result回报时。
var val = await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));
回答by Darren
This is not a direct answer to old question, but for others searching:
这不是对旧问题的直接回答,而是对其他人的搜索:
"Normally"you shouldn't do this, but sometimes you need to match a library API so you can use a wrapper function like below:
“通常”您不应该这样做,但有时您需要匹配库 API,以便您可以使用如下包装函数:
private async Task<string> WrapSomeMethod(string someParam)
{
//adding .ConfigureAwait(false) may NOT be what you want but google it.
return await Task.Run(() => SomeObj.SomeMethodAsync(someParam)).ConfigureAwait(false);
}
And then call that instead with .Result like below:
然后用 .Result 调用它,如下所示:
string blah = WrapSomeMethod(someParam).Result;

