using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WinformTest
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
#region 运用线程
/// <summary>
/// 导出Excel或其他耗时计算
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExport_Click(object sender, EventArgs e)
{
//显示正在计算的动画
this.pictureBox1.Visible = true;
//启用另一个线程,完成导出
Thread t = new Thread(new ParameterizedThreadStart(Export));
t.Start("sql where");
}
/// <summary>
/// 这里以有参举例
/// </summary>
/// <param name="strWhere"></param>
private void Export(object strWhere)
{
Thread.Sleep(1000);
this.Invoke(new Action(UpdateUI));
}
private void UpdateUI()
{
this.pictureBox1.Visible = false;
}
#endregion
#region 运用线程池,同时有返回值
private void btnExportAnother_Click(object sender, EventArgs e)
{
//显示正在计算的动画
this.pictureBox1.Visible = true;
//使用线程池,来完成导出
WaitCallback wc = new WaitCallback(this.ExportExcel);
ThreadPool.QueueUserWorkItem(wc, "sql where");
}
private void ExportExcel(object sql)
{
Thread.Sleep(1000);
//这里还以有参举例
object result = this.Invoke(new Func<int, int>(GetNumber), 11);
MessageBox.Show(result + "");
}
private int GetNumber(int num)
{
this.pictureBox1.Visible = false;
return 1111;
}
#endregion
private void btnTest_Click(object sender, EventArgs e)
{
MessageBox.Show("能操作界面");
}
}
}
源代码