正在从Task.Run获取返回值

本文关键字:获取 返回值 Run Task | 更新日期: 2023-09-27 18:26:19

我有以下代码:

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;

但我收到一个错误,说"字符串不可用"。

正在从Task.Run获取返回值

从末尾移除Result。当您await时,您将从waitable方法获得Result

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

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

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

然后用调用它。结果如下:

string blah = WrapSomeMethod(someParam).Result;

虚拟函数允许覆盖派生类中的函数。任务按顺序一次运行一个。Task.CompletedTask表示功能已完成。

public class BaseTest
{
    public virtual Task LoadDataAsync(ITestOutputHelper output) {
        for (int i = 0; i < Math.Pow(10, 5); i++)
        {
            output.WriteLine("Base {0}", i);
        }
        return Task.CompletedTask; 
    }
}
public class DerivedTest : BaseTest
{
    public override Task LoadDataAsync(ITestOutputHelper output)
    {
        for (int i = 0; i < Math.Pow(10, 6); i++)
        {
            output.WriteLine("Derived {0}", i);
        }
        return Task.CompletedTask;
    }
}

 [Fact]
    public async Task TestVirtualTask()
    {
        BaseTest parent_obj = new BaseTest();
        DerivedTest obj = new DerivedTest();
        List<Task> tasks = new List<Task>();
        tasks.Add(obj.LoadDataAsync(output));
        tasks.Add(parent_obj.LoadDataAsync(output));
        Task.WaitAll(tasks.ToArray());
        Assert.True(true);
    }

您可以添加async函数并等待task.run。这在不增加功能的情况下添加了verbage。

      public virtual async Task LoadDataAsync(ITestOutputHelper output) {
await Task.Run(() =>
            {
                for (int i = 0; i < Math.Pow(10, 6); i++)
                {
                    output.WriteLine("Derived {0}", i);
                }
                return;
            });
 }