Home > Enterprise >  Thread member is null although it was saved
Thread member is null although it was saved

Time:03-16

I have a WinForm application that when I press on "Build" it starts a function in a different 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();
}

While the function is still running, I have other button named "Stop" and when I press on it, it should stop the thread functionality:

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

But after I pressed the "Stop" button, the member m_SearchingThread is null and thread is still running.
How can it be?
I debugged it and saw that when I assign new thread to m_SearchingThread, it is not null.

EDIT:
I tried to cancel it with CancellationToken without success:

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();
}

CodePudding user response:

You are setting the local variable m_SearchingThread instead the outside variable m_SearchingThread. You have two different variables. Remove "Thread" in "Thread m_SearchingThread = new 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();
}
  • Related