65

我有以下代码:

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

如何RunLongTask从这一行取回字符串值:await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));

我试过了:

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

但是我收到一条错误消息,说“字符串不可等待”。

4

2 回答 2

104

Result从末端删除。当您从 await-able 方法中await获得回报时。Result

var val = await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));
于 2013-08-05T05:02:55.677 回答
18

这不是对旧问题的直接答案,但对于其他搜索:

“通常”您不应该这样做,但有时您需要匹配库 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;
于 2015-07-17T06:35:19.233 回答