简体   繁体   English

如何在 netcore Web 应用程序中创建任务包装器或中间件?

[英]How can I create a Task wrapper or middleware in a netcore web application?

This is a very common scenario in my solution:这是我的解决方案中非常常见的场景:

    private IActionResult MyAction()
    {
        //Run in background
        Task.Run(async () =>
        {
            try
            {

                await //..
            }
            catch (Exception ex)
            {
                //Log exception
            }
        });
        return new StatusCodeResult(StatusCodes.Status200OK);
    }

So in all my actions I am repeating the same try catch with the same logging code, I am trying to do something like this:因此,在我的所有操作中,我都使用相同的日志记录代码重复相同的 try catch,我正在尝试执行以下操作:

    private IActionResult MyAction()
    {
        Task.Run(MyExceptionHandledAsyncTask(async () =>
        {
            await //..

        }));
        return new StatusCodeResult(StatusCodes.Status200OK);
    }

Where MyExceptionHandledAsyncTask handles any exception in the task/action passed as parameter.其中 MyExceptionHandledAsyncTask 处理作为参数传递的任务/操作中的任何异常。

I have been trying but I am struggling with the returning data types and I am not sure how to do it.我一直在尝试,但我正在努力处理返回的数据类型,我不知道该怎么做。

How can I control this pattern and avoid repeating code?如何控制这种模式并避免重复代码?

You can simply create a method that receives a Func< Task > as parameter:您可以简单地创建一个接收Func<Task>作为参数的方法:

public void Test()
{
    RunSafely(() => Task.Delay(2000));
}

public Task RunSafely(Func<Task> job)
    => Task.Run(async () =>
    {
        try
        {
            await job();
        }
        catch (Exception)
        {
            //todo 
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM