代码改变世界

使用 BackgroundWorker 实现异步调用

2011-12-10 11:55  音乐让我说  阅读(361)  评论(0编辑  收藏  举报

在 WinForm 中,如果有一个耗时的操作,那么 UI 将有一种 【卡死】的感觉,解决方法是用多线程去处理那个耗时的操作。如果你不想用多线程,可以用 WinForm 中的 BackgroundWorker 来实现异步调用。

废话不多说了,直接贴代码(测试通过!):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BackGroundWorkerTestWinUI
{
    public struct AddParams
    {
        public AddParams(double num1, double num2)
        {
            this.Num1 = num1;
            this.Num2 = num2;
        }

        public double Num1;

        public double Num2;
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            try
            {
                double num1 = double.Parse(this.txtNum1.Text);
                double num2 = double.Parse(this.txtNum2.Text);
                AddParams addParam = new AddParams(num1, num2);
                backgroundWorker1.RunWorkerAsync(addParam);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            AddParams addParam = (AddParams)e.Argument;
            System.Threading.Thread.Sleep(5000); // 模拟一个好使操作
            e.Result = addParam.Num1 + addParam.Num2;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show(e.Result.ToString());
        }
    }
}

 

谢谢浏览!