Thursday, March 15, 2012

C#, Time-out function

Little summary for making an asynchronous calling function with time-out:
The original code if from here:http://www.developerfusion.com/code/4497/i-need-a-timeout/
I am just analysing it and add some notes about calling with parameter

Original code:
delegate object WorkDelegate(string arg);

public object DoWork(string arg)
{
WorkDelegate d = new WorkDelegate(DoWorkHandler);

IAsyncResult res = d.BeginInvoke(arg,null,null);
// normally control is returned right away,
// so you can do other work here...

if(res.IsCompleted == false)
{
res.AsyncWaitHandle.WaitOne(10000,false);
if(res.IsCompleted == false)
throw new ApplicationException("Timeout");
}

return d.EndInvoke((AsyncResult)res);
}
private object DoWorkHandler(string arg)
{
Thread.Sleep(5000);
return "blah " + arg;
}


1. if your DoworkHandler function need to have some parameters and return values
Define the delegate as your function looks like: eg
public delegate string WorkDelegate(string param1);

2. Pass the parameter to the beginInvoke
IAsyncResult res = d.BeginInvoke(arg,null,null);
//arg is the argument you want to pass in
//use ref or out if you want to pass parameter by reference to the callee
function

3. To check the return value, simply:
return value=d.EndInvoke((AsyncResult)res);

No comments:

Post a Comment