Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#后台线程在UserControl中运行时出错_C#_Multithreading_Background_User Controls - Fatal编程技术网

c#后台线程在UserControl中运行时出错

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

现在在我的UserControl中,有一个启动线程的按钮单击事件。此后,我不再使用Abort(),而是尝试将线程转换为后台进程,以便在关闭父窗体时关闭线程。我的代码是:

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超出了范围。在任务中创建侦听器