VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > C#编程 >
  • C#教程之C# async await 异步执行方法封装 替代 BackgroundWorker

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

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);
                }
            }
        }
    }
}
复制代码

测试代码:

复制代码
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");
        });
    }
}
复制代码

测试截图:

相关教程