在 Windows 窗体中调用 [英] Invoke in Windows Forms

查看:16
本文介绍了在 Windows 窗体中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人有使用 Invoke 的学习资源的链接吗?

Does anyone have a link to a learning resource for using Invoke?

我正在努力学习,但我看到的所有例子都无法适应我的目的.

I'm trying to learn but all the examples I have seen I have been unable to adapt for my purposes.

推荐答案

您是否尝试过 MSDN 控制.调用

Did you try MSDN Control.Invoke

我刚刚编写了一个小 WinForm 应用程序来演示 Control.Invoke.创建表单后,在后台线程上开始一些工作.完成该工作后,更新标签中的状态.

I just wrote a little WinForm application to demonstrate Control.Invoke. When the form is created, Start some work on background thread. After that work is done, Update the status in a label.

public Form1()
{
    InitializeComponent();
    //Do some work on a new thread
    Thread backgroundThread = new Thread(BackgroundWork);
    backgroundThread.Start();
}        

private void BackgroundWork()
{
    int counter = 0;
    while (counter < 5)
    {
        counter++;
        Thread.Sleep(50);
    }

    DoWorkOnUI();
}

private void DoWorkOnUI()
{
    MethodInvoker methodInvokerDelegate = delegate() 
                { label1.Text = "Updated From UI"; };

    //This will be true if Current thread is not UI thread.
    if (this.InvokeRequired)
        this.Invoke(methodInvokerDelegate);
    else
        methodInvokerDelegate();
}

这篇关于在 Windows 窗体中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆