今天在CSDN看到有为星星大哥问了个关于耗时处理的问题,其实这个问题应该使我们在项目中经常会碰到的。当时我尝试了一下,现在吧自己的实现方法写下来,供有需要的同志参考:
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 AsynCallMethod { public partial class Form1 : Form { public delegate void ComplexCallback(object objParams); public delegate void AddListItemCallback(string strItemText); public delegate void SetLabelTextCallback(string sLabelText); private bool m_bIsBusy = false; private DateTime dtStart; private ComplexCallback callback = null; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int iInterval=1000; if (int.TryParse(textBox1.Text, out iInterval)) timer1.Interval = iInterval; timer1.Enabled = true; } private void DoWork(object objParams) { m_bIsBusy = true; dtStart = DateTime.Now; callback = new ComplexCallback(DoComplexWork); callback.BeginInvoke(objParams, new AsyncCallback(EndDoComplexWork), callback); } private void DoComplexWork(object objParams) { for (int i = 1; i <10000; i++) { AddListItem(i.ToString()); } } private void EndDoComplexWork(IAsyncResult ar) { callback = ar.AsyncState as ComplexCallback; callback.EndInvoke(ar); SetLabelText((new TimeSpan(DateTime.Now.Ticks - dtStart.Ticks)).TotalSeconds.ToString() + "秒"); m_bIsBusy = false; } private void AddListItem(string sItemText) { if (listBox1.InvokeRequired) { AddListItemCallback callback = new AddListItemCallback(AddListItem); listBox1.Invoke(callback, new object[] { sItemText }); } else { listBox1.Items.Add(sItemText); } } private void SetLabelText(string sLabelText) { if (label3.InvokeRequired) { SetLabelTextCallback callback = new SetLabelTextCallback(SetLabelText); label3.Invoke(callback, new object[] { sLabelText }); } else { label3.Text = sLabelText; } } private void timer1_Tick(object sender, EventArgs e) { object objParams = null; if (!m_bIsBusy) DoWork(objParams); } private void button2_Click(object sender, EventArgs e) { timer1.Stop(); timer1.Enabled = false; } } }
窗体界面需要下面这样设置: