本文整理汇总了C#中System.Threading.Semaphore.WaitOne方法的典型用法代码示例。如果您正苦于以下问题:C# Semaphore.WaitOne方法的具体用法?C# Semaphore.WaitOne怎么用?C# Semaphore.WaitOne使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Semaphore
的用法示例。
在下文中一共展示了Semaphore.WaitOne方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ProcessBaseImplThreads
/*Object Parent;
public ProcessBaseImplThreads(Object Parent)
{
this.Parent = Parent;
}*/
public void Init(RunDelegate Delegate)
{
//Console.WriteLine("Init(" + Parent + ")");
if (mainThread == null)
{
SemaphoreGlobal = new Semaphore(1, 1);
SemaphoreGlobal.WaitOne();
mainThread = Thread.CurrentThread;
//mainMutex.WaitOne();
}
Semaphore = new Semaphore(1, 1);
Semaphore.WaitOne();
currentThread = new Thread(delegate()
{
Semaphore.WaitOne();
//currentThread.Interrupt();
Delegate();
});
currentThread.Start();
//Mutex.WaitOne();
}
示例2: Acquire
public IDisposable Acquire(string name, string waitMessage)
{
var semaphore = new Semaphore(1, 1, string.Format("Global\\{0}",name));
if (!semaphore.WaitOne(3000))
{
Log.Verbose(waitMessage);
semaphore.WaitOne();
}
return new SemaphoreReleaser(semaphore);
}
示例3: ReleaseTest
public void ReleaseTest()
{
var s = new Semaphore(1, 1);
s.WaitOne();
Console.WriteLine("Bla1");
s.Release2(1);
s.WaitOne();
Console.WriteLine("Bla2");
}
示例4: Execute
public override bool Execute()
{
if (File.Exists(PropsFile) && File.Exists(TargetsFile))
{
return true;
}
string semaphoreName = PropsFile.ToUpper().GetHashCode().ToString("X");
bool releaseSemaphore;
using (Semaphore semaphore = new Semaphore(0, 1, semaphoreName, out releaseSemaphore))
{
try
{
if (!releaseSemaphore)
{
releaseSemaphore = semaphore.WaitOne(TimeSpan.FromMinutes(5));
return releaseSemaphore;
}
return GenerateBuildPackageImportFile();
}
finally
{
if (releaseSemaphore)
{
semaphore.Release();
}
}
}
}
示例5: Runner
public Runner()
{
Console.Write("TestDvDeviceCs - starting\n");
DeviceBasic device = new DeviceBasic();
iDeviceList = new List<CpDevice>();
CpDeviceList.ChangeHandler added = new CpDeviceList.ChangeHandler(DeviceAdded);
CpDeviceList.ChangeHandler removed = new CpDeviceList.ChangeHandler(DeviceRemoved);
CpDeviceListUpnpServiceType list = new CpDeviceListUpnpServiceType("openhome.org", "TestBasic", 1, added, removed);
Semaphore sem = new Semaphore(0, 1);
sem.WaitOne(1000);
Debug.Assert(iDeviceList.Count == 1);
TestBasicCp cp = new TestBasicCp(iDeviceList[0]);
cp.TestActions();
cp.TestSubscriptions();
list.Dispose();
lock (this)
{
for (int i = 0; i < iDeviceList.Count; i++)
{
iDeviceList[i].RemoveRef();
}
}
device.Dispose();
Console.Write("TestDvDeviceCs - completed\n");
}
示例6: OutProcessHost
public OutProcessHost(MachineType type, string currentDirectory, string path)
{
if (currentDirectory == null)
currentDirectory = Directory.GetCurrentDirectory();
string lrpHostPath = null;
if (type == MachineType.IMAGE_FILE_MACHINE_I386)
{
this.isPtr32Bit = true;
lrpHostPath = FilesResolver.LrpX86HostPath;
}
else if (type == MachineType.IMAGE_FILE_MACHINE_AMD64)
{
this.isPtr32Bit = false;
lrpHostPath = FilesResolver.LrpX64HostPath;
}
else
{
var message = string.Format("Unsupported machine type = {0}", type);
throw new ArgumentException(message, "type");
}
this.pipId = Guid.NewGuid().ToString();
using (var semaphore = new Semaphore(0, 1, this.pipId))
{
var args = string.Format("\"{0}\" {1} \"{2}\"", currentDirectory, this.pipId, path);
var process = Process.Start(lrpHostPath, args);
process.Dispose();
if (!semaphore.WaitOne(PipeWaitingTimeout))
throw new TimeoutException("Timeout of LRP host waiting has been reached.");
}
var pipeName = @"\\.\pipe\" + this.pipId;
if (!WinAPI.WaitNamedPipe(pipeName, PipeWaitingTimeout))
throw new TimeoutException("Timeout of pipe waiting has been reached.");
this.pipe = WinAPI.CreateFile(pipeName, WinAPI.GENERIC_READ | WinAPI.GENERIC_WRITE, 0, IntPtr.Zero, WinAPI.OPEN_EXISTING, 0, IntPtr.Zero);
if (this.pipe == WinAPI.INVALID_HANDLE)
throw new Exception("Couldn't open pipe");
using (var transaction = new Transaction(this))
{
var buffer = this.ReadBuffer();
var isValid = buffer.ReadBoolean();
if (isValid)
{
this.signature = buffer.ReadAString();
}
else
{
var error = buffer.ReadInt32();
var message = buffer.ReadAString();
throw new Win32Exception(error, message);
}
transaction.Commit();
}
}
示例7: 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();
}
示例8: EndScene
public override void EndScene()
{
try
{
if (form.Settings.RecentSplits.Any())
config.SetString("splitspath", form.Settings.RecentSplits.Last().Path);
if (form.Settings.RecentLayouts.Any())
config.SetString("layoutpath", form.Settings.RecentLayouts.Last());
var sem = new Semaphore(0, 1);
Action formCloseAction = () =>
{
form.TopMost = false;
while (form.Visible)
form.Close();
sem.Release();
};
if (form.InvokeRequired)
form.Invoke(formCloseAction);
else
formCloseAction();
sem.WaitOne();
}
catch (Exception ex)
{
Log.Error(ex);
API.Instance.Log(ex.Message);
API.Instance.Log(ex.StackTrace);
}
}
示例9: 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;
}
示例10: waitFullSemaphore
/// <summary>
/// Analogiczna dla WaitHandle.WaitAll - wymuś uzyskanie kilku dostępów na semaforze. Po uzyskaniu tej liczby dostępów, zwolnij je
/// wszystkie. Funkcja do tego czasu blokuje.
/// </summary>
/// <param name="semaphore">Semafor</param>
/// <param name="waitCount">Ile użyć na semaforze</param>
public static void waitFullSemaphore(Semaphore semaphore, int waitCount)
{
for (int i = 0; i < waitCount; i++)
semaphore.WaitOne();
semaphore.Release(waitCount);
}
示例11: MultualExclusiongUsingSemaphore
public static void MultualExclusiongUsingSemaphore() {
count = 0;
Semaphore writeSem = new Semaphore(1, 1);
answer.Clear();
Random executionLengthRand = new Random();
Thread[] threadArray = new Thread[1000];
for (int i = 0; i < 1000; i++)
{
threadArray[i] = new Thread(
() =>
{
int temp = -1;
executionLengthRand.Next(697);
writeSem.WaitOne();
count = count + 1;
temp = count;
executionLengthRand.Next(1937);
writeSem.Release();
answer.Push(temp);
}
);
threadArray[i].Start();
}
foreach (var t in threadArray)
{
t.Join();
}
foreach (var item in answer.Reverse())
{
Console.WriteLine(item);
}
}
示例12: StartUnmanaged
public WorkerResult StartUnmanaged()
{
WorkerResult ret = null;
Unmanaged worker = new Unmanaged();
Semaphore locker = new Semaphore(0, 1);
worker.OnCallback += (IEntity param) =>
{
ret = param as WorkerResult;
if (ret == null)
{
Console.WriteLine("erro no cast!");
}
else
{
Console.WriteLine("Id da classe: {0}", ret.Id);
}
locker.Release();
};
worker.DoSomething(2);
Console.WriteLine("Chamou o Unmanaged....");
locker.WaitOne();
return ret;
}
示例13: Start
public async void Start() {
run = true;
Task.Run(async () => {
try {
listener.Start();
} catch (Exception e) {
Console.Error.WriteLine("Failed to start server: " + e.Message);
return;
}
Semaphore sem = new Semaphore(MaxConnections, MaxConnections);
while (run) {
sem.WaitOne();
listener.GetContextAsync().ContinueWith(async (T) => {
HttpListenerContext context = await T;
try {
sem.Release();
// Test for route, 404 if not found
UrlRoute route = DiscoverRoute(context.Request.Url, context.Request.HttpMethod.ToUpperInvariant());
if (route == null) {
context.Response.StatusCode = 404;
byte[] str = System.Text.Encoding.UTF8.GetBytes(GetStatusPage(404, context.Request.Url, null));
context.Response.OutputStream.Write(str, 0, str.Length);
} else {
try {
// Execute response
HttpResponse response = await ProcessRequest(route, context);
try {
// Finish stuff up
response.Response.Close();
} catch (Exception e) {
context.Response.StatusCode = 500;
byte[] str = System.Text.Encoding.UTF8.GetBytes(GetStatusPage(500, context.Request.Url, e));
context.Response.OutputStream.Write(str, 0, str.Length);
} finally {
response.Close();
}
} catch (Exception e) {
context.Response.StatusCode = 500;
byte[] str = System.Text.Encoding.UTF8.GetBytes(GetStatusPage(500, context.Request.Url, e));
context.Response.OutputStream.Write(str, 0, str.Length);
}
}
} catch (Exception e) {
context.Response.StatusCode = 500;
byte[] str = System.Text.Encoding.UTF8.GetBytes(GetStatusPage(500, context.Request.Url, e));
context.Response.OutputStream.Write(str, 0, str.Length);
} finally {
context.Response.Close();
}
return;
});
}
listener.Stop();
listener.Close();
CleanUpAfterStop();
}).Wait();
}
示例14: Create
/// <summary>
/// Try to aquire a machine-wide lock named 'name'. Returns null in case of failure (it doesn't wait at all).
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static Lock Create (string name)
{
Lock result = new Lock ();
Mutex mutex;
Semaphore semaphore;
switch (Configuration.LockingAlgorithm.ToLowerInvariant ()) {
case "mutex":
mutex = new Mutex (true, name);
if (mutex.WaitOne (1 /* ms */)) {
result.mutex = mutex;
return result;
}
return null;
case "file":
try {
result.file = File.Open (Path.Combine (Path.GetTempPath (), name + ".lock"), FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
return result;
} catch (IOException ex) {
Logger.Log ("Could not aquire builder lock: {0}", ex.Message);
return null;
}
case "fileexistence":
case "fileexistance":
string tmp = Path.Combine (Path.GetTempPath (), name + ".fileexistence-lock--delete-to-unlock");
Logger.Log ("Checking file existence for {0}", tmp);
if (File.Exists (tmp)) {
try {
if (ProcessHelper.Exists (int.Parse (File.ReadAllText (tmp)))) {
Logger.Log ("File lock corresponds to an existing process.");
return null;
}
} catch (Exception ex) {
Logger.Log ("Could not confirm that file lock corresponds to a non-existing process: {0}", ex.Message);
return null;
}
Logger.Log ("File lock corresponds to a dead process, lock acquired");
}
// there is a race condition here.
// given that the default setup is to execute a program at most once per minute,
// the race condition is harmless.
File.WriteAllText (tmp, Process.GetCurrentProcess ().Id.ToString ());
result.file_existence = tmp;
return result;
case "semaphore":
semaphore = new Semaphore (1, 1, name);
if (semaphore.WaitOne (1 /* ms */)) {
result.semaphore = semaphore;
return result;
}
return null;
default:
Logger.Log ("Unknown locking algorithm: {0} (using default 'semaphore')", Configuration.LockingAlgorithm);
goto case "semaphore";
}
}
示例15: TestSelect
public void TestSelect()
{
RecommendManager.Instance.Init(@"data source=g:\database", "");
for (int i = 0; i < 180; i++)
{
Semaphore sm = new Semaphore(0, 1);
RecommendManager.Instance.RecommendCenter.GetRecommendsBySql(SQL(i), onRecommend, () => sm.Release(), onSqlError);
sm.WaitOne();
}
}