计算密集型工作,采用多线程。
IO密集型工作,采用异步机制。
/// <summary>
/// 多线程 新开一个线程执行程序
/// </summary>
private void btnMutilthread_Click(object sender, EventArgs e)
{
var thread = new Thread(DoSomething);
thread.Start();
}
public void DoSomething()
{
var request = HttpWebRequest.Create("http://www.cnblogs.com/jx270");
var response = request.GetResponse();
var stream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(stream))
{
var content = reader.ReadToEnd();
//textBox1.Text = content;
SetText(content);
}
}
/// <summary>
/// 异步执行程序 减少占有CPU (DMA中断方式)
/// </summary>
private void btnAsyc_Click(object sender, EventArgs e)
{
var request = HttpWebRequest.Create("http://www.cnblogs.com/jx270");
request.BeginGetResponse(this.AsyncCallbackImp, request);
}
public void AsyncCallbackImp(IAsyncResult ar)
{
WebRequest request = ar.AsyncState as WebRequest;
var response = request.EndGetResponse(ar);
var stream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(stream))
{
var content = reader.ReadToEnd();
//textBox1.Text = content;
SetText(content);
}
}
void SetText(string argText)
{
if (textBox1.InvokeRequired)
{
var callBack = new DelegateMethod(SetText);
textBox1.Invoke(callBack, new[] { argText });
}
else
{
textBox1.Text = argText;
}
}
delegate void DelegateMethod(string argText);