Action<T> Fire and forget?
Can Action safely be used to essentially fire and forget a method with return type void in this way?
public static void BeginAction(Foo input, Action<Foo> action)
{
action.BeginInvoke(input, EndAction, action);
}
public static void EndAction(IAsyncResult result)
{
(result.AsyncState as A开发者_Go百科ction).EndInvoke(result);
}
Provided that you ensure you call EndInvoke()
, then yes. If you forget to call EndInvoke()
and the Action either has a return value or throws an exception, then it can leads to resources not being freed (.NET won't throw away the result or exception, it will hold them until an EndInvoke()
call claims them).
One issue you would run into is app shutdown. When the user wants to close your application, how do you either (a) wait for all of these "fire-and-forget" actions to complete, or (b) terminate them gracefully?
If you need to worry about either of those things, then "fire-and-forget" probably won't work well.
精彩评论