Maheep Saraf


I am working on an MultiThreded Windows Apllcation.Which some times randomly hangs.

I want to find out in which method it is geeting hanged. I tried but was not able to find out.

So can anyone tell me how can I define maximum time interval a method should take to execute. If it is not able to finish execution in that time duration either it should throw an exxeption or call some method... any way.

I have started on thread to listen to TCP port. On getting some data on it in XML string format it will add that data into a local DataTable Object.

In main thread(while application starts) I have defined a view on that table which is DataSource for a grid.

So problem seems while I get some data on TCP port in one thread.

But at what point that i want to know.

Thanks in advance.

Re: Common Language Runtime how can I define maximum time interval a method should take to execute


There is no simple answer to this as there is no API or property you can set for it. Instead you'll have to work out of band.

You could create a secondary thread that blocks until either the worker thread completes or the specified timeout occurs. If the timeout occurs then you know the method is taking too long. In a MT app this might be the easiest. Alternatively you could use a timer or something to call back when the interval elapses. In both cases though you'll be stuck with either trying to cancel the request or terminating the thread which could leak resources.

Michael Taylor - 1/4/07

Re: Common Language Runtime how can I define maximum time interval a method should take to execute


You cannot really terminate a function call in an arbitrary way because the call could be stuck in unmanaged code while taking a lock or waiting for a socket connect. These operations cannot be safely interrupted even in unmanaged code. The TerminateThread function could do it but you will corrupt your application in the long run. It is possible to detect when a function has executed too long quite easily by calling your function not directly but via a delegate asynchronously. When the function did not return in time you can try to terminate the called function by triggering an exit condition or simply forget this function call and start over again. Here is some code how it can be done:

class Program
delegate void Func();

static void LongRunningFunction()
while (true)
Console.WriteLine("Executing function which takes too long");

const int MaxExecutionTime = 5000; // function may take no longer than 5 seconds to execute

static void Main(string[] args)
Func f = LongRunningFunction;
IAsyncResult res = f.BeginInvoke(delegate(IAsyncResult ar)
, null);

if (res.AsyncWaitHandle.WaitOne(MaxExecutionTime, false) == false)
Console.WriteLine("Wait expired function LongRunningFunction did execute longer than {0}s", MaxExecutionTime / 1000.0f);

Alois Kraus