开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜