解决WinForms中的跨线程异常

Vic*_*tor 8 c# multithreading winforms

目前我正在使用WinForms(在C#中),我必须在后台运行该应用程序.为此我正在使用异步.当我运行应用程序时,它显示了一个例外

"跨线程操作无效:控制''从创建它的线程以外的线程访问."

我该如何解决这个错误?

Dan*_*lba 11

在对控件进行方法调用时,如果调用者与创建控件的线程不在同一个线程上,则需要使用Control.Invoke进行调用.这是一个代码示例:

// you can define a delegate with the signature you want
public delegate void UpdateControlsDelegate();

public void SomeMethod()
{
    //this method is executed by the background worker
    InvokeUpdateControls();
}

public void InvokeUpdateControls()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new UpdateControlsDelegate(UpdateControls));
    }
    else
    {
        UpdateControls();
    }
}

private void UpdateControls()
{
    // update your controls here
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.


归档时间:

查看次数:

17761 次

最近记录:

9 年,6 月 前