码迷,mamicode.com
首页 > Windows程序 > 详细

C# async await 异步执行方法封装 替代 BackgroundWorker

时间:2020-06-02 11:01:50      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:stat   cti   display   else   sync   click   ima   eric   image   

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

测试代码:

技术图片
private void button1_Click(object sender, EventArgs e)
{
    textBox1.Text = string.Empty;
    textBox1.AppendText("开始\r\n");

    for (int i = 0; i < 10; i++)
    {
        string str = string.Empty;
        int k = 0;

        BackWork.RunAsync((obj) =>
        {
            str = "i=" + obj + "\r\n";
            k = (int)obj;
        }, i, () =>
        {
            textBox1.AppendText(str);

            BackWork.RunAsync(() =>
            {
                str = "i=" + i + ", k=" + k + "\r\n";
            }, () =>
            {
                textBox1.AppendText(str);
            }, (ex) =>
            {
                textBox1.AppendText("错误:" + ex.Message + "\r\n");
            });


        }, (ex) =>
        {
            textBox1.AppendText("错误:" + ex.Message + "\r\n");
        });
    }
}
View Code

测试截图:

技术图片

 

C# async await 异步执行方法封装 替代 BackgroundWorker

标签:stat   cti   display   else   sync   click   ima   eric   image   

原文地址:https://www.cnblogs.com/s0611163/p/13029603.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!