Siva
Siva

Reputation: 259

thread abort in c#

I have written a C# program to call a function through backgndWorkerEnroll_DoWork which in turn calls another function through a thread. After I start the thread the first time, the function works properly. I then abort the thread using the thread.Abort() method and call thread.Start() method again. The previous function call still works, it doesn't abort. How can I force shutdown the thread?

public int capture()
{
    System.Threading.Thread thEnroll = new System.Threading.Thread(delegate()
    {
        // winbio.OpenSession1();
        refresult1 = winbio.Enroll1(finger, false, refresult);
        //winbio.Enroll1(finger, false, refresult, out refresult1);
    });

    thEnroll.Name = "thEnroll";
    thEnroll.Start();
    while (true)
    {
        if (!thEnroll.IsAlive)
            break;
    }
    thEnroll.Abort();
    return result;
}

private void backgndWorkerEnroll_DoWork(object sender, DoWorkEventArgs e)
{
    capture();
}

and also one more query.how to force close the backgroundDo_Work through button click event.

Upvotes: 1

Views: 410

Answers (2)

wterbeek
wterbeek

Reputation: 451

I'm not that familiar with multithreading, so corrected me if im wrong... But from what i understand is that once a Thread has been aborted it can not be started again. This might explain the behaviour you are experiencing (e.i. it works fine the first time, but not after the firt time the thread is stopped)

i googled the difference between thread.abort and thread.join (see this)

if you call Thread.Join instead, the thread will exit nicely instead of throwing an ThreadAbortedException what the site also says is that after you call abort you should also call join, or handle the ThreadAbortedException to do that.

Upvotes: 0

Dor Cohen
Dor Cohen

Reputation: 17100

It seems like it doesn't getting to your abort action since you have infinite loop:

while (true)
{
    // This will run forever
    if (!thEnroll.IsAlive)
        break;
}

this loop blocking the thread from finishing.
also your implantation seems weird, if the thread isn't alive you don't need to abort it..

Upvotes: 3

Related Questions