本文整理汇总了C#中System.Threading.Semaphore.Release方法的典型用法代码示例。如果您正苦于以下问题:C# Semaphore.Release方法的具体用法?C# Semaphore.Release怎么用?C# Semaphore.Release使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Semaphore
的用法示例。
在下文中一共展示了Semaphore.Release方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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);
}
}
示例2: Main
public static void Main()
{
const int count = 4;
_desk = new Semaphore(0, count - 1);
var forks = new List<Fork>(count);
var philosophers = new List<Philosopher>(count);
for (var i = 0; i < count; i++)
{
forks.Add(new Fork {Number = i});
}
philosophers.Add(new Philosopher(_desk, count - 1) { LeftFork = forks[count - 1], RightFork = forks[0], Number = 0, HungerLevel = 0 });
for (var i = 1; i < count; i++)
{
philosophers.Add(new Philosopher(_desk, count - 1) { LeftFork = forks[i - 1], RightFork = forks[i], Number = i, HungerLevel = count - 1 });
}
var tasks = new Task[count];
for (var i = 0; i < count; i++)
{
var idx = i;
tasks[idx] = new Task(() => philosophers[idx].Start());
}
_desk.Release(count - 1);
Parallel.ForEach(tasks, t => t.Start());
Console.ReadKey();
}
示例3: 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;
}
示例4: CoalescedAnnounce
public static CoalescedAnnounceResponse CoalescedAnnounce(this Tracker tracker, params IAnnounceRequest[] announceList)
{
InternalAnnounceResponseCollection annnounceResponses = new InternalAnnounceResponseCollection();
Semaphore requestSemaphore = new Semaphore(TrackerSettings.MaxConcurrency, TrackerSettings.MaxConcurrency);
IAsyncResult[] results = new IAsyncResult[announceList.Length];
for(int i = 0; i < announceList.Length; i++)
results[i] = tracker.BeginAnnounce(announceList[i], new AsyncCallback((result) => requestSemaphore.Release()), announceList[i].InfoHash);
foreach (IAsyncResult result in results)
{
IAnnounceResponse response = null;
try
{
response = tracker.EndAnnounce(result);
}
catch { }
if(response != null)
annnounceResponses.Add((InfoHash)result.AsyncState, new InternalAnnounceResponse(
response.Interval,
response.Complete,
response.Incomplete,
response.Peers)
);
}
return new CoalescedAnnounceResponse(annnounceResponses);
}
示例5: WidokMiniatur
/// <summary>
/// Konstruktor bezparametryczny
/// </summary>
public WidokMiniatur()
{
WyswietloneZdjecia = new List<IZdjecie>();
WszystkieZdjecia = new List<IZdjecie>();
katalogi = new Katalog[0];
tagi = new List<long>();
LargeImageList = new ImageList();
LargeImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
LargeImageList.Tag = "100%";
LargeImageList.TransparentColor = System.Drawing.Color.Transparent;
LargeImageList.ImageSize = new Size(Config.RozmiarMiniatury + 2, Config.RozmiarMiniatury + 2);
//Activate double buffering
//Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
katalog = Properties.Resources.katalog;
katalog_do_gory = Properties.Resources.katalog_do_gory;
Edycja = false;
sem = new Semaphore(0, 1);
sem.Release();
}
示例6: 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);
}
}
示例7: 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();
}
}
}
}
示例8: Core
public async static Task<List<winInfo>> Core(string SummonerName)
{
_sem = new Semaphore(0, 1);
_sem.Release();
await DoJSON(SummonerName);
List<winInfo> x = Stats.doStats(SummonerName);
return x;
}
示例9: 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();
}
示例10: Release
static void Release(int number, Semaphore semaphore)
{
Console.WriteLine(String.Format("signalling {0}...", number));
try {
semaphore.Release(number);
} catch(SemaphoreFullException sx) {
Console.WriteLine("You're pressing the button too fast! Haven't finished signalling my max limit yet!");
}
}
示例11: ReleaseWriteLock
public static void ReleaseWriteLock(this Guid id, string name = "")
{
var sem = new Semaphore(maxReaders, maxReaders, id + name);
try
{
sem.Release(maxReaders);
}
catch (SemaphoreFullException) { }
}
示例12: Setup
public void Setup()
{
prosessingFinnishedSemaphore = new Semaphore(0, 1);
queue = new CommandQueue();
queue.ProcessingFinnished +=
delegate
{
prosessingFinnishedSemaphore.Release(1);
};
}
示例13: 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();
}
}
示例14: EventLoop_ScheduleAction
public void EventLoop_ScheduleAction()
{
var ran = false;
var gate = new Semaphore(0, 1);
var el = new EventLoopScheduler();
el.Schedule(() => { ran = true;
gate.Release(); });
Assert.IsTrue(gate.WaitOne(TimeSpan.FromSeconds(2)));
Assert.IsTrue(ran);
}
示例15: TestSemephore
public void TestSemephore()
{
using (Semaphore m1 = new Semaphore(3,3, "MyAppLabel"))
{
//this will make any thread wait for 5 seconds if the app is already running to see if it stops running
m1.WaitOne();
//if the thread is done it can release the lock
m1.Release();
}
}