BackWork代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
    public class BackWork
    {
        public static void RunAsync(Action action, Action complete = null, Action<Exception> errorAction = null)
        {
            RunAsync((obj) => action(), null, complete, errorAction);
        }

        public static async void RunAsync(Action<object> action, object arg = null, Action complete = null, Action<Exception> errorAction = null)
        {
            Exception exception = null;

            Task task = Task.Run(() =>
            {
                try
                {
                    action(arg);
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
            });
            await task;

            if (exception == null)
            {
                if (complete != null)
                {
                    try
                    {
                        complete();
                    }
                    catch (Exception ex)
                    {
                        if (errorAction != null)
                        {
                            errorAction(ex);
                        }
                    }
                }
            }
            else
            {
                if (errorAction != null)
                {
                    errorAction(exception);
                }
            }
        }
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-09
  • 2022-02-13
  • 2022-12-23
  • 2023-03-10
猜你喜欢
  • 2021-11-11
  • 2022-12-23
  • 2021-06-22
  • 2022-12-23
  • 2022-12-23
  • 2021-09-14
相关资源
相似解决方案