异步处理与界面交互
当我们读取一个大数据量的数据表的时候,如果采用直接读的方式,很容易造成界面成为“白板”的现象,这也是所谓的假死。这种方式并不是十分好,因为它不能让用户非常直观的看到界面(比如加入进度条显示进度),所以需要有一种手段来防止这种现象的发生。在.net中,要实现这种方式很容易,我们只要利用BeginInvoke开启异步操作即可。
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;
using System.Runtime.Remoting.Messaging;
namespace Test.Async
{
public partial class Form1 : Form
{
private delegate string MyDelegate();
public Form1()
{
InitializeComponent();
}
private string GetData()
{
double n = 0;
for (double i = 0; i < 300000000; i++)
{
n++;
}
return n.ToString();
}
//回调函数,这里处理异步回调
private void RefreshControl(IAsyncResult iar)
{
AsyncResult result = (AsyncResult)iar;
MyDelegate dele = (MyDelegate)result.AsyncDelegate; //得到委托对象
string text = dele.EndInvoke(iar);//得到异步处理的结果
if (textBox1.InvokeRequired) //如果出现线程和界面交互
{
this.Invoke(new MethodInvoker(delegate()
{
BindTextBox(text); //绑定数据到TextBox
}));
}
else
{
BindTextBox(text); //反之直接绑定
}
}
private void BindTextBox(string text)
{
textBox1.Text = text;
timer1.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
iCount = 0;
//调用对象
MyDelegate getData = new MyDelegate(GetData);
//开始进行异步调用
getData.BeginInvoke(new AsyncCallback(RefreshControl), null);
//这里可以干别的事情
textBox1.Text = "dd";
timer1.Interval = 1000;
timer1.Enabled = true;
}
private int iCount = 0;
//这个测试异步处理的时候,做其他事情有没有影响的
private void timer1_Tick(object sender, EventArgs e)
{
++iCount;
label1.Text = iCount.ToString();
}
}
}
其实这里的执行流程就是:
首先,利用委托对象获取要执行的方法
然后,调用委托的BeginInvoke方法来开始异步执行。