C# 从c中的线程更新非活动form.text#

C# 从c中的线程更新非活动form.text#,c#,C#,我正在尝试从线程更新form.text。基本上线程需要用当前时间更新form.text。我的代码如下所示 UpdateText("My Monitor (Last Updated " + DateTime.Now.ToString("HH:mm:ss tt") + ")", Form1.ActiveForm); 方法如下 void UpdateText(String s, Control c) { if (c.InvokeRequired) {

我正在尝试从线程更新form.text。基本上线程需要用当前时间更新form.text。我的代码如下所示

UpdateText("My Monitor (Last Updated " + DateTime.Now.ToString("HH:mm:ss tt") + ")", Form1.ActiveForm);
方法如下

    void UpdateText(String s, Control c)
    {
        if (c.InvokeRequired)
        {

            this.BeginInvoke(new MethodInvoker(() => UpdateText(s, c)));

        }
        else
        {
            c.Text = s;
        }
    }

只要主应用程序窗口处于活动状态,代码就会工作。如果应用程序处于非活动状态,则会出现错误“对象引用未设置为对象的实例”

您正在调用
Form1.ActiveForm

:表示当前活动窗体的窗体,如果没有活动窗体,则为null


如果
表单
处于非活动状态,则自然为
null
。对表单使用不同的引用。如果您是从表单中调用它,请使用
this

ActiveForm
的引用保留在私有字段中,并在
线程中使用该字段

Control activeControl;
private void start_new_thread()
{
    active = Form1.ActiveForm;
    // start work under thread
}

private void work_under_thread(object state)
{

    //blocking works
    // update here
    UpdateText("My Monitor (Last Updated " + DateTime.Now.ToString("HH:mm:ss tt") + ")", activeControl);

}

您可以尝试在每个页面上使用计时器来简化事情,或者在运行线程时,您可以在要更新的表单实例中传递线程