Take the following classes as an example.
public class A
{
// ...
void Foo(S myStruct){...}
}
public class B
{
public A test;
// ...
void Bar()
{
S myStruct = new S();
test.Foo(myStruct);
}
}
Now, I want the method-call test.Foo(myStruct) to be an asynchronous call ('fire-and-forget'). The bar-method needs to return as soon as possible. Documentation around delegates, BeginInvoke, EndInvoke, the ThreadPool etc. isn't helping me find a solution.
Is this a valid solution?
// Is using the `EndInvoke` method as the callback delegate valid?
foo.BeginInvoke(myStruct, foo.EndInvoke, null);
You are not required to call
EndInvoke
; not calling it merely means:It sounds like you want to 'fire-and-forget', so the easiest way to do this is to use an anonymous delegate, for example:
This is what happens when you execute this code:
del
and the anonymous delegate (iar => ...
).del
.EndInvoke
is called the result from the method is either returned, or the exception is thrown (if one occurred).Note that the above example is very different from:
Edit: You should always call
End*
. I've never found a scenario where not calling it presents a problem, however that is an implementation detail and is relying on undocumented behavior.Finally your solution would crash the process if an exception is thrown,
you can simply pass null as the delegate if you don't care about the exception (So as a final example what you are looking for is probably:del.BeginInvoke(myStruct, null, null);
).I would say that your best option is to use the
ThreadPool
:This will queue the snippet for execution in a separate thread. Now you also have to be careful about something else: if you have multiple threads accessing the same instance of
A
and that instance modifies a variable, then you must ensure that you do proper synchronization of the variable.This is an option:
You can use the Callback model explained @ What is AsyncCallback?
That way your EndInvoke will not be in bar(), but in a separate callback method.
In the example, the EndRead (corresponding to EndInvoke is in the callback method called CompleteRead rather than the calling method TestCallbackAPM corresponding to bar)