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

c# Background thread gets an error when run in 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 那里得到一个错误 "Object reference not set to an instance of an object"。我想知道在这种情况下我哪里出错了。

您只需更改代码中的行顺序:

...
t = new Thread(() => myListiner.SpreadValue(myCurrentPort, firstTicker, secondTicker, myBeta));
t.IsBackground = true;
...

因为你需要实例化你的线程然后才使用它。