MethodInvoker 委托

MethodInvoker 提供一个简单委托,该委托用于调用含 void 参数列表的方法。 在对控件的 Invoke 方法进行调用时或需要一个简单委托又不想自己定义时可以使用该委托。

下面的代码示例演示如何使用 MethodInvoker 以调用更新应用程序窗体的标题栏的方法。

public partial class Form1 : Form
{
   private System.Threading.Timer timer;
    public Form1()
    {
        // Create a timer that will call the ShowTime method every second.
           timer = new System.Threading.Timer(ShowTime, null, 0, 1000);           
    }

    private void ShowTime(object x)
    {
        // Don't do anything if the form's handle hasn't been created 
        // or the form has been disposed.
        if (!this.IsHandleCreated && !this.IsDisposed) return;

        // Invoke an anonymous method on the thread of the form.
        this.Invoke((MethodInvoker) delegate
        {
            // Show the current time in the form's title bar.
            this.Text = DateTime.Now.ToLongTimeString();
        });
    }
}
posted @ 2014-01-15 18:01  code_flyer  阅读(579)  评论(0编辑  收藏  举报