在线程中执行代码

说明:支持跨线程访问控件。

定义代码:

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

 

posted @ 2015-06-29 16:14  0611163  阅读(522)  评论(5编辑  收藏  举报