简体   繁体   English

带锁的 C# 线程池

[英]C# Thread Pool with Locking

I'm really new to C# and am keen to learn the most effective way and utility classes to help with handling threads.我对 C# 真的很陌生,并且很想学习最有效的方法和实用程序类来帮助处理线程。

What I'm trying to do is to manage a queue of jobs.我想要做的是管理一个作业队列。 Each job has a group that it applies to.每个作业都有一个适用的组。 Jobs can run in parallel, but only one job per grouping.作业可以并行运行,但每个分组只能运行一个作业。 In a set of 1000 jobs to process, there may be 100 different groupings.在一组 1000 个要处理的作业中,可能有 100 个不同的分组。

In Pseudo code it would be:在伪代码中,它将是:

    var job = Jobs.First(job.GroupNotExecuting);
    job.RunSynchronously();

Where job.GroupNotExecuting checks to see if there is an available lock for that group.其中job.GroupNotExecuting检查该组是否有可用的锁。

What would be the best way to implement this in C#?在 C# 中实现它的最佳方法是什么?

As mentioned, I'm new to C#, so just want to get the best habit in place for a scenario like this.如前所述,我是 C# 的新手,所以只想为这样的场景养成最佳习惯。 Assistance would be appreciated!将不胜感激!

(In case it matters, I'm working in Visual Studio 2013, .NET Framework 4.5) (以防万一,我在 Visual Studio 2013、.NET Framework 4.5 中工作)

You can try using a boolean in each class as a "isBusy" flag.您可以尝试在每个类中使用一个布尔值作为“isBusy”标志。 When the job starts it sets the "isBusy" to true then does whatever it is supposed to do.当作业开始时,它将“isBusy”设置为 true,然后执行它应该执行的任何操作。 But right before the job completes it sets the "isBusy" to false.但就在作业完成之前,它将“isBusy”设置为 false。

For the calling code, it just needs to check that "isBusy" boolean.对于调用代码,它只需要检查“isBusy”布尔值。 If it's true, then the job is still running.如果为真,则作业仍在运行。 If its false, then the job is done, or has yet to be run.如果为 false,则作业已完成或尚未运行。

Or, make use of the System.Threading namespace.或者,使用 System.Threading 命名空间。 Those give you an event that can be called when the backgroundworker completes.这些给你一个可以在后台工作完成时调用的事件。

In the end I have used the SemaphorSlim class to handle the updates.最后,我使用SemaphorSlim类来处理更新。

To each job I added the process of obtaining a Semaphore from a shared / static list and waiting for it to be available.对于每个作业,我添加了从共享/静态列表中获取信号量并等待它可用的过程。 This way they could be added into the same joint pool and be processed as they became available.通过这种方式,它们可以被添加到同一个联合池中,并在它们可用时进行处理。

The downside, is that in theory a thread could be waiting for another one to process, where it may otherwise have been able to look for another job to handle in the meantime.不利的一面是,理论上一个线程可能正在等待另一个线程进行处理,否则它可能会同时寻找另一个作业来处理。

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

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