Limiting the number of threads executing a method at a single time

断了今生、忘了曾经 提交于 2019-11-30 08:33:14

Use a semaphore

http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx

Limits the number of threads that can access a resource or pool of resources concurrently.

You want a semaphore... System.Threading.Semaphore

public static class MyClass
{
    private static Semaphore sem = new Semaphore(5, 5);

    public static void SendMessage()
    {
        sem.WaitOne();

        try
        {
        }
        finally
        {
            sem.Release(1);
        }
    }
}

Alternatively, if you only want a single thread to be able to call a method at a given time, .NET also exposes a concept equivalent with java's synchronized attribute:

[System.Runtime.CompilerServices.MethodImpl(MethodImpl.Synchronized)]

The Semaphore class was designed for exactly this scenario.

Design Pattern Approach: - Use command pattern with five Executor threads and wrap your requests in Command classes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!