简体   繁体   中英

C# generic for running function in another thread

I have a few generic function for running methods in background threads. Are there any dangers here outside of normal thread sync issues?

    public static void ThreadRunReturn<TReturn, TArgument>(Func<TArgument, TReturn> func, TArgument arg, bool background = true)
    {
        Thread th = new Thread(unused => func(arg));
        th.IsBackground = background;
        th.Start(th);
    }
    public static void ThreadRunReturn<TReturn, TArgument1, TArgument2>(Func<TArgument1, TArgument2, TReturn> func, TArgument1 arg1, TArgument2 arg2, bool background = true)
    {
        Thread th = new Thread(unused => func(arg1, arg2));
        th.IsBackground = background;
        th.Start(th);
    }

    public static void ThreadRun<TArgument>(Action<TArgument> action, TArgument arg, bool background = true)
    {
        Thread th = new Thread(unused => action(arg));
        th.IsBackground = background;
        th.Start(th);
    }
    public static void ThreadRun<TArgument1, TArgument2>(Action<TArgument1, TArgument2> action, TArgument1 arg1, TArgument2 arg2, bool background = true)
    {
        Thread th = new Thread(unused => action(arg1, arg2));
        th.IsBackground = background;
        th.Start(th);
    }

background threads do not keep the application alive. if you have long running background processes running and your application terminates, it will not wait for those background threads to complete - it will kill them. just something to keep in mind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM