Why does the delegate need to call the EndInvoke before the method fires? If i need to call the EndInvoke (which blocks the thread) then its not really an asynchronous call is it?
Here is the code im trying to run.
class Program
{
private delegate void GenerateXmlDelegate();
static void Main(string[] args)
{
GenerateXmlDelegate worker = new GenerateXmlDelegate(GenerateMainXml);
IAsyncResult result = worker.BeginInvoke(null, null);
}
private static void GenerateMainXml()
{
Thread.Sleep(10000);
Console.WriteLine("GenerateMainXml Called by delegate");
}
}
The reason you need to call
EndInvoke
is to avoid memory leaks; .Net will store information about the function's result (or exception) until you callEndInvoke
.You can call
EndInvoke
in the completion handler that you give toBeginInvoke
and retain the asyncronous nature.EDIT:
For example:
If you want to fire an async call and forget about it, you can use the ThreadPool, like this:
As SLaks said,
EndInvoke
insures against memory leaks.BeginInvoke
is still asynchronous; consider the following code:If this code were written without the
BeginInvoke
/EndInvoke
calls,PerformSlowCalculation
would have to finish beforeMain
could do the rest of its "lots of stuff"; this way, the two can be happening at the same time.Now, in your example using a
GenerateXmlDelegate
, you still needEndInvoke
even though you're not returning anything. The way to do this is: