I found the following code snippet on CodeProject on calling methods asynchronously at ...
http://www.codeproject.com/Articles/14931/Asynchronous-Method-Invocation
private void CallFooWithOutAndRefParameters()
{
// create the paramets to pass to the function
string strParam1 = "Param1";
int intValue = 100;
ArrayList list = new ArrayList();
list.Add("Item1");
// create the delegate
DelegateWithOutAndRefParameters delFoo =
new DelegateWithOutAndRefParameters(FooWithOutAndRefParameters);
// call the beginInvoke function!
IAsyncResult tag =
delFoo.BeginInvoke(strParam1,
out intValue,
ref list,
null, null);
// normally control is returned right away,
// so you can do other work here...
// calling end invoke notice that intValue and list are passed
// as arguments because they might be updated within the function.
string strResult =
delFoo.EndInvoke(out intValue, ref list, tag);
// write down the parameters:
Trace.WriteLine("param1: " + strParam1);
Trace.WriteLine("param2: " + intValue);
Trace.WriteLine("ArrayList count: " + list.Count);
Trace.WriteLine("return value: " + strResult);
}
There are a couple of things I don't understand about this code.
Per the comment control is returned immediately to the calling code when it hits the BeginInvoke line.
Does that mean that the code that follows (EndInvoke followed by some trace logging) only runs after the FooWithOutAndRefParameters call completes...automagically (even though that code resides in the same method). It looks a little confusing to me. (I have always used callbacks for this kind of thing.)
Using this method do I HAVE to call EndInvoke. Can I just invoke the method asyncronously and forget it happened? Any downsides to this?
If I don't call EndInvoke (as is shown in this method) should I then always have a callback? Even if the callback does nothing.
If the answers YOU SHOULD...then do you call EndInvoke OR define a callback? (The advantage to defining a callback being that you are notified of the result)
BTW I know I could check for errors or log resuls in the EndInvoke or callback (and I might in fact do that). What I was wondering is ARE THERE RISKS from not calling EndInvoke or defining a callback (memory leaks for example)? What is the best practice.
Seth
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…