简体   繁体   English

使 class 中的所有方法在 c# 的同一线程上运行

[英]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.我想创建具有自己的线程的 singleton,并执行每个方法(假设这是数据库,并且每个添加/修改操作都需要从同一个线程调用),该线程可以在构造函数中创建,我也想要那个singleton 中的每个方法都将在这个特定线程上执行。

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.据我了解,新的 System.Threading.Thread.Thread() 使我能够启动线程,但启动后,我无法自由地对它进行下一个工作。 How to queue new work to that thread?如何将新工作排队到该线程? This should work like myThread.Queue(()=> doWork());这应该像 myThread.Queue(()=> doWork()); but i dont see api like that.但我没有看到这样的 api。

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. TryTake 将无限期地阻塞(或 unitl collection.CompleteAdding()被调用,尽管有接受超时值的重载。

        var collection = new BlockingCollection<Action>();

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

        }).Start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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