在線程中執行代碼,線程執行代碼
定義代碼:

![]()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace PackageOperMgr.util
{
/// <summary>
/// 跨線程訪問控件的委托
/// </summary>
public delegate void InvokeDelegate();
/// <summary>
/// 跨線程訪問控件類
/// </summary>
public class InvokeUtil
{
/// <summary>
/// 跨線程訪問控件
/// </summary>
/// <param name="ctrl">Form對象</param>
/// <param name="de">委托</param>
public static void Invoke(Control ctrl, InvokeDelegate de)
{
if (ctrl.IsHandleCreated)
{
ctrl.BeginInvoke(de);
}
}
/// <summary>
/// 在線程中執行代碼
/// </summary>
public static void ExecuteCode(Control ctrl, InvokeDelegate de)
{
new Thread(new ThreadStart(delegate()
{
InvokeUtil.Invoke(ctrl, de);
})).Start();
}
}
}
View Code
如何使用:

![]()
InvokeUtil.ExecuteCode(this, new InvokeDelegate(delegate()
{
//這裡寫您要執行的代碼
string s = "aa" + "bb"; //例子
NextBtn.Enabled = false; //例子
}));
View Code