【问题标题】:How to chain synchronous and aynchronous methods correctly together in CSharpFunctionalExtensions?如何在 CSharpFunctionalExtensions 中正确地将同步和异步方法链接在一起?
【发布时间】:2019-07-22 21:14:48
【问题描述】:

我熟悉CSharpFunctionalExtensions。有synchronous usageasynchronous usage 的明显例子。但是,在某些情况下,这些需要链接在一起(同步和异步结合)。我在我的Main 方法中使用Task.FromResult 是否正确地做到了这一点?还是我应该调用不同的功能扩展方法?对于这种情况,它可以工作并且应用程序输出预期的 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();
        }
    }

【问题讨论】:

    标签: c# functional-programming


    【解决方案1】:

    你不需要等待同步操作

    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();
            }
        }
    

    【讨论】:

    • 您的代码做了一些根本不同的事情。我希望 DuplicateAsync 只执行 OnSuccessGetMyLength。这就是为什么我想把它们锁起来。您不执行此链接。
    • 从性能角度不建议等待同步操作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 2011-03-28
    相关资源
    最近更新 更多