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 call EndInvoke
.
You can call EndInvoke
in the completion handler that you give to BeginInvoke
and retain the asyncronous nature.
EDIT:
For example:
class Program {
private delegate void GenerateXmlDelegate();
static void Main(string[] args) {
GenerateXmlDelegate worker = new GenerateXmlDelegate(GenerateMainXml);
IAsyncResult result = worker.BeginInvoke(delegate {
try {
worker.EndInvoke();
} catch(...) { ... }
}, null);
}
private static void GenerateMainXml() {
Thread.Sleep(10000);
Console.WriteLine("GenerateMainXml Called by delegate");
}
}
If you want to fire an async call and forget about it, you can use the ThreadPool, like this:
ThreadPool.QueueUserWorkItem(delegate { GenerateMainXml(); });
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…