线程成员为空,虽然它被保存

Thread member is null although it was saved

我有一个 WinForm 应用程序,当我按下“构建”时,它会在不同的线程中启动一个函数:

Thread m_SearchingThread;
private void buttonBuild_Click(object sender, EventArgs e)
{
    Engine.BuildRPCDBStatusUpdate += Engine_BuildDBStatusUpdate;
    // Saves the thread as class member
    Thread m_SearchingThread = new Thread( o => Engine.BuildDataBase(textBoxFolderForSearch.Text));
    m_SearchingThread.Start();
}

虽然功能仍然是 运行,但我还有另一个名为“停止”的按钮,当我按下它时,它应该会停止线程功能:

private void buttonStop_Click(object sender, EventArgs e)
{
    if (m_SearchingThread != null)
    {
        m_SearchingThread.Abort();
    }
}

但是在我按下“停止”按钮后,成员m_SearchingThread为空,线程仍然是运行。
怎么可能?
我调试了它,发现当我将新线程分配给 m_SearchingThread 时,它不是空的。

编辑:
我尝试用 CancellationToken 取消它但没有成功:

CancellationTokenSource cts = new CancellationTokenSource();
private void buttonBuild_Click(object sender, EventArgs e)
{
    ...
    ThreadPool.QueueUserWorkItem(s =>
    {
        CancellationToken token = (CancellationToken)s;
        if (token.IsCancellationRequested)
            return;
        Engine.BuildDataBase(textBoxFolderForSearch.Text);
        token.WaitHandle.WaitOne(1000);
    }, cts.Token);
}

private void buttonStop_Click(object sender, EventArgs e)
{
    cts.Cancel();
}

您正在设置局部变量 m_SearchingThread 而不是外部变量 m_SearchingThread。你有两个不同的变量。删除“Thread m_SearchingThread = new Thread...”中的“Thread”

Thread m_SearchingThread;
private void buttonBuild_Click(object sender, EventArgs e)
{
    Engine.BuildRPCDBStatusUpdate += Engine_BuildDBStatusUpdate;
    // Saves the thread as class member
    /*Thread */m_SearchingThread = new Thread( o => Engine.BuildDataBase(textBoxFolderForSearch.Text));
    m_SearchingThread.Start();
}