c#后台线程在UserControl中运行时出错
现在在我的UserControl中,有一个启动线程的按钮单击事件。此后,我不再使用Abort(),而是尝试将线程转换为后台进程,以便在关闭父窗体时关闭线程。我的代码是:c#后台线程在UserControl中运行时出错,c#,multithreading,background,user-controls,C#,Multithreading,Background,User Controls,现在在我的UserControl中,有一个启动线程的按钮单击事件。此后,我不再使用Abort(),而是尝试将线程转换为后台进程,以便在关闭父窗体时关闭线程。我的代码是: public Thread t; private void btnInitiate_Click(object sender, EventArgs e) { UDPListener myListiner = new UDPListener(this); t.IsBackground = tr
public Thread t;
private void btnInitiate_Click(object sender, EventArgs e)
{
UDPListener myListiner = new UDPListener(this);
t.IsBackground = true;
t = new Thread(() => myListiner.SpreadValue(myCurrentPort, firstTicker, secondTicker, myBeta));
t.Start();
}
但是当我运行应用程序时,我从
t.IsBackground=true
中得到一个错误,它说“对象引用未设置为对象的实例”。我想知道在这种情况下我错在哪里。您只需要更改代码中的行顺序:
...
t = new Thread(() => myListiner.SpreadValue(myCurrentPort, firstTicker, secondTicker, myBeta));
t.IsBackground = true;
...
因为您需要实例化线程,然后才使用它。启动任务后,您的方法完成了,但任务仍在运行,myListiner超出了范围。在任务中创建侦听器