简体   繁体   中英

Making all methods from a class to run on the same thread in c#

i want to create singleton that has its own thread, and executes every method (lets assume this is database, and every add/modify action need to be called from the same thread), that thread can be created inside constructor, also i want that every method from that singleton will execute on this specific thread.

From what i understand, the new System.Threading.Thread.Thread() gives me ability to start thread, but after start, i cannot freely ququee next work to it. How to queue new work to that thread? This should work like myThread.Queue(()=> doWork()); but i dont see api like that.

The below simplified code shows how you can do this. TryTake will block indefinitely (or unitl collection.CompleteAdding() is called, although there are overloads that accept a timeout value.

        var collection = new BlockingCollection<Action>();

        new Thread(() =>
        {
            while (collection.TryTake(out Action a, -1))
            {
                     a.Invoke();
            }
        }

        }).Start();

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