如何在CSharpFunctionalExtensions中将同步方法和异步方法正确地链接在一起?

时间:2019-02-28 21:19:57

标签: c# functional-programming

我熟悉CSharpFunctionalExtensions。有synchronous usageasynchronous usage的清晰示例。但是,在某些情况下,这些需要链接在一起(同步和异步结合在一起)。我通过在Task.FromResult方法中使用Main来正确执行此操作吗?还是应该调用其他功能扩展方法?在这种情况下,它可以正常工作,并且应用程序会输出预期的 8 ,但这并不意味着这是我可以在所有软件应用程序中使用的最佳方法。

    class Program
    {
        // Assume this is a normal synchronous operation
        static Result<int> GetMyLength(string text) => Result.Ok(text.Length);

        // Assume this a typical async operation, such as a web request
        static async Task<Result<int>> DuplicateThisAsync(int x) => await Task.FromResult(Result.Ok(x * 2));

        static async Task Main()
        {
            var tryResult = await Task.FromResult(GetMyLength("Daan"))
                                .OnSuccess(a => DuplicateThisAsync(a));
            Console.WriteLine(tryResult.Value);
            Console.ReadLine();
        }
    }

1 个答案:

答案 0 :(得分:0)

您无需等待同步操作

class Program
    {
        // Assume this is a normal synchronous operation
        static Result<int> GetMyLength(string text) => Result.Ok(text.Length);

        // Assume this a typical async operation, such as a web request
        static async Task<Result<int>> DuplicateThisAsync(int x) => await Task.FromResult(Result.Ok(x * 2));

        static async Task Main()
        {
            var tryResult = GetMyLength("Daan")
            if tryResult.Success // Something similar if .Success is not available
            {
               tryResult = await DuplicateThisAsync(tryResult.Value));
               Console.WriteLine(tryResult.Value);
            }
            Console.ReadLine();
        }
    }