.net 正在从Task.Run获取返回值

gr8qqesn  于 2022-11-19  发布在  .NET
关注(0)|答案(3)|浏览(125)

下面的代码:

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;

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

58wvjzkj

58wvjzkj1#

从末尾移除Result。当您执行await时,您将从可等待的方法中取回Result

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

c86crjj02#

这不是对老问题的直接回答,而是对别人的刨根问底:

**“通常”**您不应该这样做,但有时您需要匹配库API,以便可以使用如下所示的 Package 函数:

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;
4uqofj5v

4uqofj5v3#

虚函数允许您重写派生类中的函数。任务按顺序一次运行一个。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;
            });
 }

相关问题