c# - 如何防止操作参数成为异步 lambda?

标签 c# lambda async-await

我正在编写一个小包装器( MyWrapper )用于单元测试。其目的是用 try-catch 包装测试代码,以捕获一个特定异常 ( MySpecialException ),然后忽略测试。

为什么我这样做应该与这个问题无关。

鉴于下面的代码,我如何防止其他人传递 Action并像这样使用异步? 或者换句话说:我如何强制他们使用 MyWrapper.ExecuteAsync(Func<Task>)相反?


using System;
using System.Threading.Tasks;
using NUnit.Framework;

namespace PreventAsyncActionLambdaExample
{
    [TestFixture]
    public class Example
    {
        [Test]
        public async Task ExampleTest()
        {
            // How do I prevent others from passing an action and using async like this?
            // Or in other words: How do I force them to use MyWrapper.ExecuteAsync(Func<Task>) instead?
            MyWrapper.Execute(async () =>
            {
                var cut = new ClassUnderTest();

                await cut.DoSomethingAsync();

                Assert.Fail("Problem: This line will never be reached");
            });
        }
    }

    public static class MyWrapper
    {
        // This method SHOULD NOT, BUT WILL be used in this example
        public static void Execute(Action action)
        {
            try
            {
                action();
            }
            catch (MySpecialException)
            {
            Assert.Ignore("Ignored due to MySpecialException");
            }
        }

        // This method SHOULD BE USED in this example, BUT WILL NOT be used.
        public static async Task ExecuteAsync(Func<Task> func)
        {
            try
            {
                await func();
            }
            catch (MySpecialException)
            {
                Assert.Ignore("Ignored due to MySpecialException");
            }
        }
    }

    public class MySpecialException : Exception
    {
        // This is another exception in reality which is not relevant for this example
    }

    public class ClassUnderTest
    {
        public Task DoSomethingAsync()
        {
            return Task.Delay(20); // Simulate some work
        }
    }
}

最佳答案

恐怕您无法在编译时真正阻止这种情况,但您可以编写另一个重载,在这种情况下将拾取该重载,以告诉他们应该使用ExecuteAsync相反:

public static Task Execute(Func<Task> action)
{
    throw new Exception("Please use the ExecuteAsync(Func<Task> func) method instead if you will be passing async lambdas");
}

关于c# - 如何防止操作参数成为异步 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588195/

相关文章:

c# - 返回 FileInfo HttpResult 时写入 header 时出错

c# - 如何使用异步方法纠正编写测试?

c# - 如何像 FPS 游戏一样计算光标增量?

lambda - 有/没有捕获变量的 lambda 之间的签名差异?

c# - Lambda 表达式树解析

ruby-on-rails - 用于 activerecord 回调的新 lambda 文字语法

c# - 并行运行时 IronPDF 死锁

javascript - 从 AsyncStorage 检索 JWT 以使用 ApolloClient 创建 httpLink 中间件时出现问题

c# - MonoMac WebView - 显示控制台或 Web 检查器?

c# - .NET Color 中的 RGB 格式