Typesafe fire-and-forget asynchronous delegate invocation in C#

后端 未结 7 1840
陌清茗
陌清茗 2020-12-28 19:41

I recently found myself needing a typesafe \"fire-and-forget\" mechanism for running code asynchronously.

Ideally, what I would want to do is somet

7条回答
  •  庸人自扰
    2020-12-28 19:55

    How about something like:

    public static class FireAndForgetMethods
    {
        public static void FireAndForget(this Action act,T arg1)
        {
            var tsk = Task.Factory.StartNew( ()=> act(arg1),
                                             TaskCreationOptions.LongRunning);
        }
    }
    

    Use it like:

    Action foo = (t) => { Thread.Sleep(t); };
    foo.FireAndForget(100);
    

    To add type safety, just expand out the helper methods. T4 is probably best here.

提交回复
热议问题