How can I abort a thread to ensure the application doesn't get stuck?

128 Views Asked by At

Given below is the code that uses a WorkingBlock function. The application uses C# 3.0.

The WorkingBlock method code works well except in some circumstances with which the application freezes.

Initially, the WorkingBlock method was called directly in CallerFunction. The following structure was set up to mitigate the issue of the application freezing.

However, even after this, the control will be present inside the WorkingBlock method of the DoAction Thread and the application would still be stuck. I have even tried to set DoAction.IsBackground to true but nothing works.

Is there a way to forcefully abort the DoAction Thread so that the application will not be stuck? The control should leave the CallerFunction method altogether.

private void CallerFunction(Record record)
{
    //some work done
    bool SeeResult = CalledFunction(record);
} 

private bool CalledFunction(Record record)
{
    Waithandles CheckWaithandles = new Waithandle [] {new ManualResetEvent(false), new ManualResetEvent(false)};

    Thread TimeOutCheck = new Thread(() => {
        //Has a StopWatch to check timeout. Thread will stop once StopWatch has reached an Elapsed Limit 
        (ManualResetEvent)CheckWaithandles[1]).Set();
    });

    Thread DoAction = new Thread(() => {
        WorkingBlock(record);
        (ManualResetEvent)CheckWaithandles[0]).Set();
    });

    TimeOutCheck.Start();
    DoAction.Start();

    int WaitHandleCalled = WaitHandle.WaitAny(CheckWaithandles);
    if(WaitHandleCalled == 0)
        return true;
    else
    {
        return false;
        DoAction.Abort();
    }
}
0

There are 0 best solutions below