我有以下代码:

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;

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

最佳答案

从最后删除Result。当您使用await时,您将从可等待方法中获取Result

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

07-27 13:58