简体   繁体   中英

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:

    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.

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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