Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread timeout in c#

I'm new to threading in C#. Is there anyway of setting a timeout for a thread without blocking the calling thread (in C# 3.5)?

If not, is it logical to execute a function using a thread and within that function create a thread and join it to overcome this main thread blocking issue? To illustrate:

Instead of:

Public void main()
{
        ...
        Thread thrd1 = new Thread(new ThreadStart(targetObj.targetFunc));
        thrd1.Start();
        thrd1.Join();
        ...
}

Using something like:

Public void main()
{
        ...
        Thread thrd1 = new Thread(new ThreadStart(middleObj.waiter));
        thrd1.Start();
        ...
}

//And in the middleObj.waiter():
Public void waiter()
{
        Thread thrd2 = new Thread(new ThreadStart(targetObj.targetFunc));
        thrd2.Start();
        thrd2.Join();
}
like image 686
DeveloperInToronto Avatar asked Jul 07 '10 13:07

DeveloperInToronto


1 Answers

I checked and the simplest and most comprehensive way of doing it was the solution I mentioned in the description of the question. A middle level thread can easily wait for the second thread without any interruption over the main thread; and it can kill the second thread if it does not respond within the required time. That's exactly what I needed. I used it and it worked without a problem.

like image 107
DeveloperInToronto Avatar answered Oct 04 '22 08:10

DeveloperInToronto