与ContinueWith的组合等待

问题描述 投票:2回答:1

我遇到了下面要理解的异步代码(此示例已简化):

class Program
{
    static async Task Main(string[] args)
    {
        var foo = new Foo();

        try
        {
            var bar = new Bar();
            await foo.ComputeNumber(bar.GetNumberAsync());
        }
        catch (Exception e)
        {
            Console.WriteLine($"Logged exception: {e}");
        }
        Console.WriteLine($"The number is {foo.Number}");
        Console.ReadKey();
    }
}

public class Foo
{
    public int Number { get; private set; } = 0;

    public async Task ComputeNumber(Task<int> inputTask)
    {
        await inputTask.ContinueWith(x => Number = x.Result);
    }
}

public class Bar
{
    public async Task<int> GetNumberAsync()
    {
        return await Task.Factory.StartNew(() =>
        {
            if (DateTime.Now.Date.DayOfWeek != DayOfWeek.Monday)
            {
                throw new Exception("This function works only on Mondays.");
            }
            return 17;
        });
    }
}

此代码可以按我预期的方式工作(至少希望如此),但是我认为应该通过以下方式之一解决此问题(我认为两者都是正确的)。 Bar类将保持不变。

第一个(异步/等待)方法:

class Program
{
    static async Task Main(string[] args)
    {
        var foo = new Foo();

        try
        {
            var bar = new Bar();
            await foo.ComputeNumber(bar.GetNumberAsync());
        }
        catch (Exception e)
        {
            Console.WriteLine($"Logged exception: {e}");
        }
        Console.WriteLine($"The number is {foo.Number}");
        Console.ReadKey();
    }
}

public class Foo
{
    public int Number { get; private set; } = 0;

    public async Task ComputeNumber(Task<int> inputTask)
    {
        Number = await inputTask;
    }
}

第二(基于任务的方法:] >>

class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo();
        var bar = new Bar();
        foo.ComputeNumber(bar.GetNumberAsync());

        Console.WriteLine($"The number is {foo.Number}");
        Console.ReadKey();
    }
}

public class Foo
{
    public int Number { get; private set; } = 0;

    public void ComputeNumber(Task<int> inputTask)
    {
        inputTask.ContinueWith(x =>
        {
            if (x.IsFaulted)
            {
                Console.WriteLine($"Logged exception: {x.Exception}");
            }
            else
            {
                Number = x.Result;
            }
        });
    }
}

我很欣赏为什么可以使用这种方式编写使用异步代码的原始示例的所有解释。

我遇到了下面要尝试理解的异步代码(此示例已简化):class Program {静态异步Task Main(string [] args){var foo = new Foo(); ...

c# async-await task-parallel-library
1个回答
3
投票

您可以将await视为一种语言功能,它取代了ContinueWith的大多数用法,因此将两者混合使用似乎是不必要的。

© www.soinside.com 2019 - 2024. All rights reserved.