




















目前项目里面有个需求,需要多线程操作数据库,等待数据库操作完毕之后,主线程才能继续执行以后的操作。
想了想,最后决定使用两个信号量来完成这个需求。
具体需求如下 :
运行截图如下:

具体代码如下:
using System;
using System.Threading;
using System.Collections.Generic;public class UseSemaphore
{
private static readonly Semaphore s1 = new Semaphore(3,3);
private static readonly Semaphore s2 = new Semaphore(0,1);
private const int TaskCount = 10;
private static int count;public static void Main()
{
Console.WriteLine("MainThread Start");
count = TaskCount;
for(int i = 0; i < TaskCount; ++i)
{
s1.WaitOne();
ThreadPool.QueueUserWorkItem(Process, null);
}
s2.WaitOne();
Console.WriteLine("MainThread");
Console.ReadKey();
}
private static void Process(object obj)
{
Console.WriteLine("ThreadPool {0} Start", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(100);
Console.WriteLine("ThreadPool {0} Stop", Thread.CurrentThread.ManagedThreadId);
s1.Release();
Interlocked.Decrement(ref count);
if(count == 0)
{
Console.WriteLine("s2 Release");
s2.Release();
}
}
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。