本文整理汇总了C#中Semaphore类的典型用法代码示例。如果您正苦于以下问题:C# Semaphore类的具体用法?C# Semaphore怎么用?C# Semaphore使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Semaphore类属于命名空间,在下文中一共展示了Semaphore类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Barrier
public Barrier(uint count)
{
threadCount = count;
mutex = new Semaphore(1, 1);
sem = new Semaphore(0, (int) count);
sem2 = new Semaphore(0, (int)count);
}
示例2: Run
private int Run(int iCount, int mCount, string semName, int iRandom)
{
// Testing createdNew
bool createdNew;
int iRet = -1, count = iCount;
Semaphore sem = null;
if (iRandom > 0)
semName = Common.GenerateUnicodeString(iRandom);
try
{
using(sem = new Semaphore(iCount, mCount, semName, out createdNew))
{
if (iCount > 0)
{
sem.WaitOne();
count--;
}
int iPrev = sem.Release();
if (iPrev == count && createdNew)
iRet = 100;
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected exception thrown: " + ex.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例3: StartCore
protected override void StartCore()
{
// initialize the requests counter with a dud count
// as to not set the countdown event immediately
_requestsCounter = new CountdownEvent(1);
_stopSignal = new ManualResetEvent(false);
_pumpCounter = new Semaphore(ConcurrentPumpCount, ConcurrentPumpCount);
// initialize an http listener
_listener = new HttpListener();
foreach (var url in Urls)
_listener.Prefixes.Add(url);
// initialize and start the request pump
_pumpThread = new Thread(_ => requestPump()) {
IsBackground = false,
Name = RequestPumpThreadName,
Priority = ThreadPriority.AboveNormal
};
_listener.Start();
_pumpThread.Start();
}
示例4: Main
public static void Main(string[] args)
{
_threadPool = new Semaphore(MaxThreads, MaxThreads);
using (_s3Client = AWSClientFactory.CreateAmazonS3Client(ConfigurationManager.AppSettings["AWSAccessKey"], ConfigurationManager.AppSettings["AWSSecretKey"]))
{
for (int level = StartLevel; level <= EndLevel; ++level)
{
double tileSize = WebMercatorDelta * Math.Pow(2, 1 - level);
int startRow = Convert.ToInt32(Math.Truncate((WebMercatorDelta - ExtentMaxY) / tileSize)) - TilePaddingY;
int endRow = Convert.ToInt32(Math.Truncate((WebMercatorDelta - ExtentMinY) / tileSize)) + 1 + TilePaddingY;
int startColumn = Convert.ToInt32(Math.Truncate((ExtentMinX + WebMercatorDelta) / tileSize)) - TilePaddingX;
int endColumn = Convert.ToInt32(Math.Truncate((ExtentMaxX + WebMercatorDelta) / tileSize)) + 1 + TilePaddingX;
for (int r = startRow; r <= endRow; ++r)
{
for (int c = startColumn; c <= endColumn; ++c)
{
_threadPool.WaitOne();
Thread t = new Thread(new ParameterizedThreadStart(CopyImage));
t.Start(new UserData(level, r, c));
Console.Write(String.Format("{0}Level {1} Row {2} Column {3}", new String('\b', 40), level, r, c).PadRight(80));
}
}
}
}
Console.WriteLine((new String('\b', 40) + "Done").PadRight(80));
Console.Read();
}
示例5: Run
private int Run()
{
int iRet = -1;
string sName = Common.GetUniqueName();
// open a closed semaphore
try
{
using (Semaphore sem1 = new Semaphore(10, 10, sName))
{
}
Semaphore sem2 = Semaphore.OpenExisting(sName);
}
catch (WaitHandleCannotBeOpenedException)
{
//Expected
iRet = 100;
}
catch (Exception e)
{
Console.WriteLine("Caught unexpected exception: " +
e.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例6: Run
private int Run()
{
int iRet = -1;
string sName = Common.GetUniqueName();
// open a Mutex with the same name as a Semaphore
using (Semaphore sem = new Semaphore(10, 10, sName))
{
try
{
Mutex mut = Mutex.OpenExisting(sName);
}
catch(WaitHandleCannotBeOpenedException)
{
//Expected
iRet = 100;
}
catch (Exception e)
{
Console.WriteLine("Caught exception where WaitHandleCannotBeOpenedException was expected: " +
e.ToString());
}
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例7: Run
private int Run(int initalValue, int maxValue, string semName, int iRandom)
{
int iRet = -1;
Semaphore sem = null;
if (iRandom > 0)
semName = Common.GenerateUnicodeString(iRandom);
try
{
using (sem = new Semaphore(initalValue, maxValue, semName))
{
Console.WriteLine("Semaphore was created!");
}
}
catch(ArgumentException)
{
// Expected
iRet = 100;
}
catch(Exception e)
{
Console.WriteLine("Unexpected exception thrown: " +
e.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例8: Downloader
/// <summary>
/// Initializes a new instance of <see cref="Downloader"/> with a configuration,
/// allowing the given number of parallel downloads.
/// </summary>
/// <param name="parallelDownloads">The maximum number of parallel downloads.
/// This value must be in the interval of <c>1</c> and <c>9999</c>.</param>
public Downloader(int parallelDownloads)
{
if (parallelDownloads < 1 || parallelDownloads > 9999)
{
throw new ArgumentOutOfRangeException("parallelDownloads",
"The number of parallel downloads must be at least 1 and less than 10000.");
}
Debug.WriteLine("Initializing downloader for " + parallelDownloads + " parallel downloads.");
UrlResolver = new List<IUrlResolver>();
ParallelDownloads = parallelDownloads;
webClients = new WebClient[parallelDownloads];
downloadEvents = new AutoResetEvent[parallelDownloads];
for (int i = 0; i < parallelDownloads; i++)
{
downloadEvents[i] = new AutoResetEvent(false);
}
availableTasks = new Semaphore(0, int.MaxValue);
Debug.WriteLine("Starting worker threads...");
for (int i = 0; i < parallelDownloads; i++)
{
var no = i;
var t = new Thread(() => Worker(no));
t.Name = string.Format("DownloadWorker_{0:00}", no);
t.Priority = ThreadPriority.BelowNormal;
t.Start();
}
DownloadAttempts = 1;
}
示例9: Server
public Server(int port)
{
this.port = port;
m_ServerSemaphore = new Semaphore(20,20);
errorHandler = new ErrorPageHandler();
ext = XMLParser.DeserializeExtensionXML();
}
示例10: Run
private int Run(int iCount, int mCount)
{
// Testing basic scenario
int iRet = -1;
Semaphore sem = null;
try
{
using (sem = new Semaphore(iCount, mCount))
{
int iPrev = 0, count = iCount;
// Do a wait one if we can
if (iCount > 0)
{
sem.WaitOne();
count--;
}
iPrev = sem.Release();
if (iPrev == count)
iRet = 100;
}
}
catch (Exception ex)
{
Console.WriteLine("FAIL: CtorTest1(" + iCount + "," + mCount + ") - Unexpected exception thrown: " + ex.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例11: Run
private int Run(int initCount, int maxCount)
{
int iRet = -1;
Semaphore sem = null;
try
{
using (sem = new Semaphore(initCount, maxCount))
{
Console.WriteLine("Semaphore was created!");
}
}
catch(ArgumentException)
{
// Expected
iRet = 100;
}
catch(Exception e)
{
// other exceptions are not valid
Console.WriteLine("Unexpected exception thrown: " +
e.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}
示例12: WaitPanelThread
public WaitPanelThread(Point origin, int delay, bool positiveAxis, bool horizontal, Panel panel, Plane plane, Semaphore semaphoreThis, Semaphore semaphoreNext, Semaphore semaphoreTerminal, Buffer bufferPrevious, Buffer bufferNext, Buffer bufferTerminal, int length, int terminalID)
{
this.origin = origin;
this.delay = delay;
this.positiveAxis = positiveAxis;
this.panel = panel;
this.plane = plane;
this.panel.Paint += new PaintEventHandler(this.panel_Paint);
if (horizontal)
{
this.xDelta = positiveAxis ? +10 : -10;
this.yDelta = 0;
}
else
{
this.xDelta = 0;
this.yDelta = positiveAxis ? +10 : -10;
}
this.semaphoreThis = semaphoreThis;
this.semaphoreNext = semaphoreNext;
this.semaphoreTerminal = semaphoreTerminal;
this.bufferPrevious = bufferPrevious;
this.bufferNext = bufferNext;
this.bufferTerminal = bufferTerminal;
this.length = length;
this.terminalID = terminalID;
}
示例13: Fetch
public WebSite Fetch(string url, int depth = 0)
{
var webSite = new WebSite();
webSite.Domain = WebTools.DomainHelper.GetDomain(url);
var pages = new List<WebPage>();
webSite.Pages = pages;
var queue = new ConcurrentQueue<FetchItem>();
var visited = new HashSet<string>();
queue.Enqueue(new FetchItem { Depth = 0, Url = url });
Semaphore semaphore = new Semaphore(1, MaxThreads);
FetchItem item;
var mutex = new object();
while (true)
{
lock(mutex)
{
semaphore.WaitOne();
if (!queue.TryDequeue(out item))
{
break;
}
new Thread(() => FetchAndAdd(semaphore, item, depth, webSite.Domain, visited, queue, webSite.Pages)).Start();
}
}
return webSite;
}
示例14: ServerStart
private Socket _server; //服务器Socket监听对象
#endregion Fields
#region Constructors
/// <summary>
/// 初始化通信监听
/// </summary>
/// <param name="max">最大连接数</param>
/// <param name="port">监听的端口</param>
public ServerStart(int max,int port)
{
_server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
_maxClient = max; //实例化socket监听对象
_pool=new UserTokenPool(max); //实例化连接池对象
//实例化一个最大允许max个线程允许的信号量
//并将它的计数器的初始值设为max
//这就是说除了调用该信号量的线程都将被阻塞
_acceptClients = new Semaphore(max,max);
//初始化创建max个数的链接对象并存入连接池
for (var i = 0; i < max; i++)
{
//初始化token信息
var token=new UserToken();
//绑定接收事件
token.ReceiveSAEA.Completed+=
new EventHandler<SocketAsyncEventArgs>(IO_Comleted);
//绑定发送事件
token.SendSAEA.Completed+=
new EventHandler<SocketAsyncEventArgs>(IO_Comleted);
token.LD = LD;
token.LE = LE;
token.encode = encode;
token.decode = decode;
token.sendProcess = ProccessSend;
_pool.Push(token);
}
}
示例15: Run
private int Run(int iCount, int mCount, string semName, int iRandom)
{
// Testing basic string scenario
int iRet = -1, count = iCount;
Semaphore sem1 = null, sem2 = null;
if (iRandom > 0)
semName = Common.GenerateUnicodeString(iRandom);
try
{
using (sem1 = new Semaphore(iCount, mCount, semName))
{
using (sem2 = (semName != null && semName != string.Empty) ? Semaphore.OpenExisting(semName) : sem1)
{
if (iCount > 0)
{
sem2.WaitOne();
count--;
}
int iPrev = sem2.Release();
if (iPrev == count)
iRet = 100;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Unexpected exception thrown: " + ex.ToString());
}
Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
return iRet;
}