从Task.Run获取返回值

时间:2013-08-05 04:58:24

标签: c# .net task-parallel-library async-await

我在这里有以下代码

    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!";
    }

在这一行:

await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));

如何获取RunLongTask的字符串值?

我试过

var val = await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture))).Result;

但我收到错误“字符串不等待”

2 个答案:

答案 0 :(得分:63)

从最后删除Result。当您await时,您将从等待方法中获得Result

var val = await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));

答案 1 :(得分:9)

这不是对旧问题的直接回答,而是对其他搜索:

“正常”您不应该这样做,但有时您需要匹配库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);
}

然后用.Result调用它,如下所示:

string blah = WrapSomeMethod(someParam).Result;