Here are the examples of the csharp api System.Threading.EventWaitHandle.Reset() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
706 Examples
19
Source : IOThreadTimer.cs
with MIT License
from CoreWCF
with MIT License
from CoreWCF
public static int WaitAny(WaitableTimer[] waitableTimers)
{
do
{
long earliestDueTime = waitableTimers[0].DueTime;
for (int i = 1; i < waitableTimers.Length; i++)
{
if (waitableTimers[i].dead)
{
return 0;
}
if (waitableTimers[i].DueTime < earliestDueTime)
{
earliestDueTime = waitableTimers[i].DueTime;
}
waitableTimers[i].Reset();
}
long waitDurationInMillis = (earliestDueTime - DateTime.UtcNow.Ticks) / TimeSpan.TicksPerMillisecond;
if (waitDurationInMillis < 0) // Already preplaceded the due time
{
return 0;
}
Contract.replacedert(waitDurationInMillis < int.MaxValue, "Waiting for longer than is possible");
WaitAny(waitableTimers, (int)waitDurationInMillis);
// Always loop around and check wait time again as values might have changed.
} while (true);
}
19
Source : AudioManager.cs
with MIT License
from csinkers
with MIT License
from csinkers
protected override void Subscribed()
{
_doneEvent.Reset();
Task.Run(AudioThread);
base.Subscribed();
}
19
Source : SingleThreadEventExecutorBenchmark.cs
with MIT License
from cuteant
with MIT License
from cuteant
static void Run(ITestExecutor executor)
{
var mre = new ManualResetEvent(false);
var actionIn = new BenchActionIn(executor, mre);
executor.Execute(actionIn);
if (!mre.WaitOne(TimeSpan.FromMinutes(1)))
{
throw new TimeoutException($"{executor.Name} benchmark timed out.");
}
mre.Reset();
var actionOut = new BenchActionOut(mre);
for (int i = 0; i < Iterations; i++)
{
executor.Execute(actionOut);
}
if (!mre.WaitOne(TimeSpan.FromMinutes(1)))
{
throw new TimeoutException($"{executor.Name} benchmark timed out.");
}
}
19
Source : SnackbarMessageQueue.cs
with MIT License
from cxwl3sxl
with MIT License
from cxwl3sxl
private void UiElementOnMouseEnter(object sender, MouseEventArgs mouseEventArgs)
{
_waitHandle.Reset();
}
19
Source : SnackbarMessageQueue.cs
with MIT License
from cxwl3sxl
with MIT License
from cxwl3sxl
internal Action Pause()
{
if (_isDisposed) return () => { };
if (Interlocked.Increment(ref _pauseCounter) == 1)
_pausedEvent.Set();
return () =>
{
if (Interlocked.Decrement(ref _pauseCounter) == 0)
_pausedEvent.Reset();
};
}
19
Source : SnackbarMessageQueue.cs
with MIT License
from cxwl3sxl
with MIT License
from cxwl3sxl
private async void PumpAsync()
{
while (!_isDisposed)
{
var eventId = WaitHandle.WaitAny(new WaitHandle[] { _disposedEvent, _messageWaitingEvent });
if (eventId == 0) continue;
var exemplar = _pairedSnackbars.FirstOrDefault();
if (exemplar == null)
{
Trace.TraceWarning(
"A snackbar message as waiting, but no Snackbar instances are replacedigned to the message queue.");
_disposedEvent.WaitOne(TimeSpan.FromSeconds(1));
continue;
}
//find a target
var snackbar = await FindSnackbar(exemplar.Dispatcher);
//show message
if (snackbar != null)
{
var message = _snackbarMessages.First.Value;
_snackbarMessages.RemoveFirst();
if (_latestShownItem == null
|| message.IgnoreDuplicate
|| !Equals(_latestShownItem.Item1.Content, message.Content)
|| !Equals(_latestShownItem.Item1.ActionContent, message.ActionContent)
|| _latestShownItem.Item2 <= DateTime.Now.Subtract(_messageDuration))
{
await ShowAsync(snackbar, message);
_latestShownItem = new Tuple<SnackbarMessageQueueItem, DateTime>(message, DateTime.Now);
}
}
else
{
//no snackbar could be found, take a break
_disposedEvent.WaitOne(TimeSpan.FromSeconds(1));
}
if (_snackbarMessages.Count > 0)
_messageWaitingEvent.Set();
else
_messageWaitingEvent.Reset();
}
}
19
Source : TaskService.cs
with MIT License
from dahall
with MIT License
from dahall
private void ThreadProc()
{
completed.Reset();
object obj = null;
try { obj = Activator.CreateInstance(objType); } catch { }
if (obj == null) return;
ITaskHandler taskHandler = null;
try { taskHandler = (ITaskHandler)obj; } catch { }
try
{
if (taskHandler != null)
{
taskHandler.Start(status, Data);
completed.WaitOne(Timeout);
taskHandler.Stop(out ReturnCode);
}
}
finally
{
if (taskHandler != null)
Marshal.ReleaseComObject(taskHandler);
Marshal.ReleaseComObject(obj);
}
}
19
Source : RegistryEventMonitor.cs
with MIT License
from dahall
with MIT License
from dahall
private void StartRaisingEvents()
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
throw new PlatformNotSupportedException();
if (keyName == null) throw new ArgumentNullException(nameof(RegistryKeyName));
if (!IsSuspended && EnableRaisingEvents)
{
lock (threadLock)
{
breakEvent.Reset();
hkey = RegistryHandleFromName(keyName, remoteMachine);
if (hkey == null || hkey.IsClosed || hkey.IsInvalid) throw new InvalidOperationException($"Unable to connect to registry key specified in {nameof(RegistryKeyName)}");
for (var i = 0; i < eventCount; i++)
{
if (threads[i] is not null && threads[i].IsAlive)
threads[i].Join(500);
threads[i] = new Thread(MonitorRegThreadProc) { IsBackground = false };
threads[i].Start(i);
}
if (!WaitHandle.WaitAll(threadsStarted, 5000))
{
StopRaisingEvents();
throw new InvalidOperationException("Threads waiting for changes failed to start within reasonable time.");
}
}
}
19
Source : RegTests.cs
with MIT License
from dahall
with MIT License
from dahall
[Test]
public void TestRegMonitor()
{
const string subkey = @"Software\Vanara";
const string subkey2 = "Test";
var m = new RegistryEventMonitor { RegistryKeyName = @"HKEY_CURRENT_USER\" + subkey, IncludeSubKeys = true };
var ev1 = new AutoResetEvent(false);
var ev2 = new AutoResetEvent(false);
m.ValueChanged += (s, e) => { TestContext.WriteLine("Value changed."); ev1.Set(); };
m.SubkeyChanged += (s, e) => { TestContext.WriteLine("Subkey changed."); ev2.Set(); };
m.EnableRaisingEvents = true;
using (var k = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(subkey, true))
{
var sk = k.CreateSubKey(subkey2);
sk.SetValue("uint", 2U, Microsoft.Win32.RegistryValueKind.DWord);
sk.DeleteValue("uint");
replacedert.That(WaitHandle.WaitAll(new WaitHandle[] { ev1, ev2 }, 5000));
m.IncludeSubKeys = false;
replacedert.That(m.EnableRaisingEvents, Is.False);
ev1.Reset();
m.EnableRaisingEvents = true;
k.SetValue("uint", 2U, Microsoft.Win32.RegistryValueKind.DWord);
k.DeleteValue("uint");
replacedert.That(ev1.WaitOne(100));
ev1.Reset();
sk.SetValue("uint", 2U, Microsoft.Win32.RegistryValueKind.DWord);
replacedert.That(ev1.WaitOne(100), Is.False);
ev2.Reset();
k.DeleteSubKey(subkey2);
replacedert.That(ev2.WaitOne(1000));
}
}
19
Source : Common.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth
protected static void SendLoop(int connectionId, TcpClient client, SafeQueue<byte[]> sendQueue,
ManualResetEvent sendPending)
{
NetworkStream stream = client.GetStream();
try
{
while (client.Connected)
{
sendPending.Reset();
byte[][] messages;
if (sendQueue.TryDequeueAll(out messages))
if (!SendMessagesBlocking(stream, messages))
return;
sendPending.WaitOne();
}
}
catch (ThreadAbortException) { }
catch (ThreadInterruptedException) { }
catch (Exception exception)
{
Logger.Log("SendLoop Exception: connectionId=" + connectionId + " reason: " + exception);
}
}
19
Source : FinsResponse.cs
with GNU General Public License v3.0
from DCNick3
with GNU General Public License v3.0
from DCNick3
public void Reset()
{
Sid = 0;
Data = null;
WaitEvent.Reset();
}
19
Source : Parallel.cs
with GNU General Public License v3.0
from DeepHydro
with GNU General Public License v3.0
from DeepHydro
public static void For( int start, int stop, ForLoopBody loopBody )
{
lock ( sync )
{
// get instance of parallel computation manager
Parallel instance = Instance;
instance.currentIndex = start - 1;
instance.stopIndex = stop;
instance.loopBody = loopBody;
// signal about available job for all threads and mark them busy
for ( int i = 0; i < threadsCount; i++ )
{
instance.threadIdle[i].Reset( );
instance.jobAvailable[i].Set( );
}
// wait until all threads become idle
for ( int i = 0; i < threadsCount; i++ )
{
instance.threadIdle[i].WaitOne( );
}
}
}
19
Source : CubismBuiltinAsyncTaskHandler.cs
with MIT License
from DenchiSoft
with MIT License
from DenchiSoft
private static void Work()
{
while (!CallItADay)
{
// Try to dequeue a task.
var task = DequeueTask();
// Execute task if available.
if (task != null)
{
task.Execute();
}
// Wait for a task to become available.
else
{
Signal.WaitOne();
Signal.Reset();
}
}
}
19
Source : PythonConsole.cs
with MIT License
from dimven
with MIT License
from dimven
string ReadLineFromTextEditor()
{
int result = WaitHandle.WaitAny(waitHandles);
if (result == lineReceivedEventIndex)
{
lock (previousLines)
{
string line = previousLines[0];
previousLines.RemoveAt(0);
if (previousLines.Count == 0)
{
lineReceivedEvent.Reset();
}
return line;
}
}
return null;
}
19
Source : BncsEvent.cs
with GNU General Public License v3.0
from dkuwahara
with GNU General Public License v3.0
from dkuwahara
public void Reset()
{
_event.Reset();
}
19
Source : McpEvent.cs
with GNU General Public License v3.0
from dkuwahara
with GNU General Public License v3.0
from dkuwahara
public void Reset()
{
_event.Reset();
_packet = null;
}
19
Source : GameServer.cs
with GNU General Public License v3.0
from dkuwahara
with GNU General Public License v3.0
from dkuwahara
public void LeaveGame()
{
GameExitEvent.Reset();
Connection.WritePacket(new byte[] { 0x69 });
GameExitEvent.WaitOne();
Connection.Terminate();
_listener.Join();
}
19
Source : GameServer.cs
with GNU General Public License v3.0
from dkuwahara
with GNU General Public License v3.0
from dkuwahara
internal void GameLogon(uint gameHash, ushort gameToken, Character character)
{
LoadSuccessEvent.Reset();
Connection.WritePacket(new GameLogonPacket(gameHash, gameToken, character));
LoadSuccessEvent.WaitOne();
LoadCompleteEvent.Reset();
Connection.WritePacket(new byte[] { 0x6B });
LoadCompleteEvent.WaitOne();
Log.Verbose("Game load complete");
}
19
Source : WindowsTimer.cs
with MIT License
from Dnawrkshp
with MIT License
from Dnawrkshp
public void WaitForTrigger()
{
this.triggerEvent.WaitOne();
this.triggerEvent.Reset();
}
19
Source : CallbackScheduler.cs
with MIT License
from dolittle
with MIT License
from dolittle
void CallbackLoop()
{
while (!_hostApplicationStopping.IsCancellationRequested)
{
_waitForNewCallback.Reset();
var timeToNextCall = TimeSpan.FromMilliseconds(int.MaxValue);
try
{
foreach (var group in _groups.Values)
{
var timeToNextGroupCall = group.TimeToNextCall;
if (timeToNextGroupCall < TimeSpan.Zero)
{
_metrics.IncrementTotalSchedulesMissed();
_metrics.AddToTotalSchedulesMissedTime(-timeToNextGroupCall);
}
if (timeToNextGroupCall <= _timeResolution)
{
group.CallRegisteredCallbacks();
timeToNextGroupCall = group.TimeToNextCall;
}
if (timeToNextGroupCall < timeToNextCall)
{
timeToNextCall = timeToNextGroupCall;
}
}
}
catch (Exception ex)
{
_metrics.IncrementTotalCallbackLoopsFailed();
_logger.CallbackLoopFailed(ex);
}
if (timeToNextCall > _timeResolution)
{
_waitForNewCallback.WaitOne(timeToNextCall - _timeResolution);
}
}
}
19
Source : SUDP.cs
with MIT License
from DonnYep
with MIT License
from DonnYep
public int Send(Stream stream, int packetSize, int groupSize)
{
error = false;
int dataSize = packetSize - 1;
int i, read, readSum;
byte flag = 0;//UDPå
äøēę åæåč,å
å«ē»åŗå·,å
åŗå·(å³ē»å
åŗå·),åéē»ęę åæ
int resendCount = 0;//éåꬔę°ę č®°
try
{
//åÆåØē”®č®¤å
ę„ę¶ēŗæēØ
thListen = new Thread(new ThreadStart(Listen));
thListen.IsBackground = true;
thListen.Start();
groupSeq = 0;
stream.Seek(0, SeekOrigin.Begin);
confirmEvent.Reset();
while (true)
{
if (error)
return -1;
readSum = 0;//č®°å½čÆ»ååčę°ä»„ä¾æéåę¶Streamēåé
for (i = 0; i < groupSize; i++)
{
flag = (byte)(((byte)groupSeq) << 4 | (((byte)i) << 1));
byte[] buffer = new byte[packetSize];
read = stream.Read(buffer, 0, dataSize);
readSum += read;
if (read == dataSize)
{
if (stream.Position == stream.Length)//å·²ē»čÆ»å®
{
flag |= 0x01;//ē»ęę č®°ä½ē½®1
buffer[read] = flag;//ę°ę®å
ę åæåčę¾äŗęÆäøŖå
ēęå
client.Send(buffer, read + 1);
break;
}
buffer[read] = flag;
client.Send(buffer, read + 1);
}
else if (read > 0)//å·²ē»čÆ»å®
{
flag |= 0x01;//ē»ęę č®°ä½ē½®1
buffer[read] = flag;//ę°ę®å
ę åæåčę¾äŗęÆäøŖå
ēęå
client.Send(buffer, read + 1);
break;
}
else
{
break;
}
}
if (error)
return -1;
if (confirmEvent.WaitOne(confirmTimeOut))//ę¶å°ē”®č®¤
{
if ((int)(flag & 0x01) == 1)//åéå®ęÆ
break;
groupSeq = (groupSeq + 1) % 16;
resendCount = 0;
}
else//ęŖę¶å°ē”®č®¤
{
if (resendCount >= maxResendCount)//č¶
åŗę大éåꬔę°
{
thListen.Abort();
return -1;
}
//éå
stream.Seek(-1 * readSum, SeekOrigin.Current);
resendCount++;
}
}
//åéå®ęÆ,å
³éē”®č®¤å
ę„ę¶ēŗæēØ
thListen.Abort();
}
catch//å¼åøø
{
thListen.Abort();
return -1;
}
return 0;
}
19
Source : FirmataDevice.cs
with MIT License
from dotnet
with MIT License
from dotnet
public Version QueryFirmataVersion()
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
// Try a few times (because we have to make sure the receiver's input queue is properly synchronized and the device
// has properly booted)
for (int i = 0; i < 20; i++)
{
lock (_synchronisationLock)
{
_dataReceived.Reset();
_firmataStream.WriteByte((byte)FirmataCommand.PROTOCOL_VERSION);
_firmataStream.Flush();
bool result = _dataReceived.WaitOne(TimeSpan.FromSeconds(FIRMATA_INIT_TIMEOUT_SECONDS));
if (result == false)
{
// Attempt to send a SYSTEM_RESET command
_firmataStream.WriteByte(0xFF);
Thread.Sleep(20);
continue;
}
if (_actualFirmataProtocolMajorVersion == 0)
{
// The device may be resetting itself as part of opening the serial port (this is the typical
// behavior of the Arduino Uno, but not of most newer boards)
Thread.Sleep(100);
continue;
}
return new Version(_actualFirmataProtocolMajorVersion, _actualFirmataProtocolMinorVersion);
}
}
throw new TimeoutException("Timeout waiting for firmata version");
}
19
Source : FirmataDevice.cs
with MIT License
from dotnet
with MIT License
from dotnet
internal Version QueryFirmwareVersion(out string firmwareName)
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
// Try 3 times (because we have to make sure the receiver's input queue is properly synchronized)
for (int i = 0; i < 3; i++)
{
lock (_synchronisationLock)
{
_dataReceived.Reset();
_firmataStream.WriteByte((byte)FirmataCommand.START_SYSEX);
_firmataStream.WriteByte((byte)FirmataSysexCommand.REPORT_FIRMWARE);
_firmataStream.WriteByte((byte)FirmataCommand.END_SYSEX);
bool result = _dataReceived.WaitOne(TimeSpan.FromSeconds(FIRMATA_INIT_TIMEOUT_SECONDS));
if (result == false || _firmwareVersionMajor == 0)
{
// Wait a bit until we try again.
Thread.Sleep(100);
continue;
}
firmwareName = _firmwareName;
return new Version(_firmwareVersionMajor, _firmwareVersionMinor);
}
}
throw new TimeoutException("Timeout waiting for firmata firmware version");
}
19
Source : FirmataDevice.cs
with MIT License
from dotnet
with MIT License
from dotnet
internal void QueryCapabilities()
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
lock (_synchronisationLock)
{
_dataReceived.Reset();
_firmataStream.WriteByte((byte)FirmataCommand.START_SYSEX);
_firmataStream.WriteByte((byte)FirmataSysexCommand.CAPABILITY_QUERY);
_firmataStream.WriteByte((byte)FirmataCommand.END_SYSEX);
bool result = _dataReceived.WaitOne(DefaultReplyTimeout);
if (result == false)
{
throw new TimeoutException("Timeout waiting for device capabilities");
}
_dataReceived.Reset();
_firmataStream.WriteByte((byte)FirmataCommand.START_SYSEX);
_firmataStream.WriteByte((byte)FirmataSysexCommand.replacedOG_MAPPING_QUERY);
_firmataStream.WriteByte((byte)FirmataCommand.END_SYSEX);
result = _dataReceived.WaitOne(DefaultReplyTimeout);
if (result == false)
{
throw new TimeoutException("Timeout waiting for PWM port mappings");
}
}
}
19
Source : FirmataDevice.cs
with MIT License
from dotnet
with MIT License
from dotnet
public byte[] SendCommandAndWait(FirmataCommandSequence sequence, TimeSpan timeout, out CommandError error)
{
if (!sequence.Validate())
{
throw new ArgumentException("The command sequence is invalid", nameof(sequence));
}
lock (_synchronisationLock)
{
if (_firmataStream == null)
{
throw new ObjectDisposedException(nameof(FirmataDevice));
}
_dataReceived.Reset();
// Use an explicit iteration, avoids a memory allocation here
for (int i = 0; i < sequence.Sequence.Count; i++)
{
_firmataStream.WriteByte(sequence.Sequence[i]);
}
_firmataStream.Flush();
bool result = _dataReceived.WaitOne(timeout);
if (result == false)
{
throw new TimeoutException("Timeout waiting for command answer");
}
error = _lastCommandError;
return _lastResponse.ToArray();
}
}
19
Source : Perf.EventWaitHandle.cs
with MIT License
from dotnet
with MIT License
from dotnet
[Benchmark]
public bool Set_Reset()
{
EventWaitHandle are = _are;
return are.Set() && are.Reset();
}
19
Source : D3DImage.cs
with MIT License
from dotnet
with MIT License
from dotnet
private void SendPresent(object sender, EventArgs args)
{
Debug.replacedert(_isDirty);
Debug.replacedert(_isWaitingForPresent);
Debug.replacedert(_lockCount == 0);
//
// If we were waiting for present when the bitmap changed, SetBackBuffer removed
// us from waiting for present. So if this is true then the NEW bitmap has been
// dirtied before it has been sent to the render thread. We need to delay the
// present until after the update resource because the D3DImage resource is still
// referencing the old bitmap.
//
if (_waitingForUpdateResourceBecauseBitmapChanged)
{
return;
}
UnsubscribeFromCommittingBatch();
unsafe
{
DUCE.MILCMD_D3DIMAGE_PRESENT data;
DUCE.Channel channel = sender as DUCE.Channel;
Debug.replacedert(_duceResource.IsOnChannel(channel));
data.Type = MILCMD.MilCmdD3DImagePresent;
data.Handle = _duceResource.GetHandle(channel);
// We need to make sure the event stays alive in case we get collected before
// the composition thread processes the packet
IntPtr hDuplicate;
IntPtr hCurrentProc = MS.Win32.UnsafeNativeMethods.GetCurrentProcess();
if (!MS.Win32.UnsafeNativeMethods.DuplicateHandle(
hCurrentProc,
_canWriteEvent.SafeWaitHandle,
hCurrentProc,
out hDuplicate,
0,
false,
MS.Win32.UnsafeNativeMethods.DUPLICATE_SAME_ACCESS
))
{
throw new Win32Exception();
}
data.hEvent = (ulong)hDuplicate.ToPointer();
// Send packed command structure
// Note that the command is sent in its own batch (sendInSeparateBatch == true) because this method is called under the
// context of the MediaContext.CommitChannel and the command needs to make it into the current set of changes which are
// being commited to the compositor. If the command would not be added to a separate batch, it would go into the
// "future" batch which would not get submitted this time around. This leads to a dead-lock situation which occurs when
// the app calls Lock on the D3DImage because Lock waits on _canWriteEvent which the compositor sets when it sees the
// Present command. However, since the compositor does not get the Present command, it will not set the event and the
// UI thread will wait forever on the compositor which will cause the application to stop responding.
channel.SendCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_D3DIMAGE_PRESENT),
true /* sendInSeparateBatch */
);
}
_isDirty = false;
// Block on next Lock
_canWriteEvent.Reset();
}
19
Source : RTCP.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
private void CheckForSamples()
{
try
{
Thread.Sleep(CHECK_FORSAMPLE_PERIOD); // Wait until the first sample is likely to be ready.
while (m_checkForSamples)
{
RTCPReport report = CheckForAvailableSample(m_windowLastSeqNum);
if (report != null && RTCPReportReady != null)
{
try
{
RTCPReportReady(report);
}
catch { }
}
m_checkForSampleEvent.Reset();
m_checkForSampleEvent.WaitOne(CHECK_FORSAMPLE_PERIOD, false);
}
}
catch (Exception excp)
{
logger.Debug("Exception CheckForSamples. " + excp.Message);
}
}
19
Source : RTSPClient.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
private void SendKeepAlives()
{
try
{
Thread.CurrentThread.Name = "rtspclient-keepalive";
// Set the initial pause as half the keep-alive interval.
Thread.Sleep(RTP_KEEP_ALIVE_INTERVAL * 500);
while (!_isClosed)
{
_rtspSession.SendRTPRaw(new byte[] { 0x00, 0x00, 0x00, 0x00 });
// Also send an OPTIONS request on the RTSP connection to prevent the remote server from timing it out.
RTSPRequest optionsRequest = new RTSPRequest(RTSPMethodsEnum.OPTIONS, _url);
RTSPHeader optionsHeader = new RTSPHeader(_cseq++, _rtspSession.SessionID);
optionsRequest.Header = optionsHeader;
System.Diagnostics.Debug.WriteLine(optionsRequest.ToString());
var rtspRequestBuffer = Encoding.UTF8.GetBytes(optionsRequest.ToString());
_rtspStream.Write(rtspRequestBuffer, 0, rtspRequestBuffer.Length);
var buffer = new byte[2048];
var bytesRead = _rtspStream.Read(buffer, 0, 2048);
if (bytesRead > 0)
{
System.Diagnostics.Debug.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesRead));
var rtspMessage = RTSPMessage.ParseRTSPMessage(buffer, null, null);
if (rtspMessage.RTSPMessageType == RTSPMessageTypesEnum.Response)
{
var optionsResponse = RTSPResponse.ParseRTSPResponse(rtspMessage);
//logger.Debug("RTSP Response received for OPTIONS keep-alive request: " + optionsResponse.StatusCode + " " + optionsResponse.Status + " " + optionsResponse.ReasonPhrase + ".");
}
}
else
{
logger.Warn("Zero bytes were read from the RTSP client socket in response to an OPTIONS keep-alive request.");
}
_sendKeepAlivesMRE.Reset();
_sendKeepAlivesMRE.WaitOne(RTP_KEEP_ALIVE_INTERVAL * 1000);
}
}
catch (Exception excp)
{
logger.Error("Exception RTSPClient.SendKeepAlives. " + excp);
}
}
19
Source : MainProcess.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
public void Run()
{
_eventStopService.Reset();
_eventThreadExit.Reset();
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
// config info for .net core https://www.cnblogs.com/Leo_wl/p/5745772.html#_label3
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddXmlFile("Config/gb28181.xml", false, reloadOnChange: true);
var config = builder.Build();//// Console.WriteLine(config["sipaccount:ID"]);
var sect = config.GetSection("sipaccounts");
//Config Service & and run
ConfigServices(config);
//Start the main serice
_mainTask = Task.Factory.StartNew(() => MainServiceProcessing());
//wait the process exit of main
_eventExitMainProcess.WaitOne();
}
19
Source : RTPSink.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
private void ListenerTimeout()
{
try
{
logger.Debug("Listener timeout thread started for RTP stream " + m_streamId);
// Wait for the first RTP packet to be received.
m_lastPacketReceived.WaitOne();
// Once we've got one packet only allow a maximum of NO_RTP_TIMEOUT between packets before shutting the stream down.
while(!StopListening)
{
if(!m_lastPacketReceived.WaitOne(NO_RTP_TIMEOUT*1000, false))
{
logger.Debug("RTP Listener did not receive any packets for " + NO_RTP_TIMEOUT + "s, shutting down stream.");
Shutdown();
break;
}
// Shutdown the socket even if there is still RTP but the stay alive limit has been exceeded.
if(RTPMaxStayAlive > 0 && DateTime.Now.Subtract(m_startRTPSendTime).TotalSeconds > RTPMaxStayAlive)
{
logger.Warn("Shutting down RTPSink due to preplaceding RTPMaxStayAlive time.");
Shutdown();
break;
}
m_lastPacketReceived.Reset();
}
}
catch(Exception excp)
{
logger.Error("Exception ListenerTimeout. " + excp.Message);
throw excp;
}
}
19
Source : SIPNotifierClient.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
private void StartSubscription()
{
try
{
logger.Debug("SIPNotifierClient starting for " + m_resourceURI.ToString() + " and event package " + m_sipEventPackage.ToString() + ".");
while (!m_exit)
{
m_attempts = 0;
m_subscribed = false;
m_waitForSubscribeResponse.Reset();
Subscribe(m_resourceURI, m_expiry, m_sipEventPackage, m_subscribeCallID, null);
m_waitForSubscribeResponse.WaitOne();
if (!m_exit)
{
m_waitForNextSubscribe.Reset();
if (m_subscribed)
{
// Schedule the subscription based on its expiry.
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.NotifierClient, SIPMonitorEventTypesEnum.SubscribeFailed, "Rescheduling next attempt for a successful subscription to " + m_resourceURI.ToString() + " in " + (m_expiry - RESCHEDULE_SUBSCRIBE_MARGIN) + "s.", null));
m_waitForNextSubscribe.WaitOne((m_expiry - RESCHEDULE_SUBSCRIBE_MARGIN) * 1000);
}
else
{
//Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.NotifierClient, SIPMonitorEventTypesEnum.SubscribeFailed, "Rescheduling next attempt for a failed subscription to " + m_resourceURI.ToString() + " in " + RETRY_POST_FAILURE_INTERVAL + "s.", null));
//m_waitForNextSubscribe.WaitOne(RETRY_POST_FAILURE_INTERVAL * 1000);
break;
}
}
}
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.NotifierClient, SIPMonitorEventTypesEnum.SubscribeFailed, "Subscription attempts to " + m_resourceURI.ToString() + " for " + m_sipEventPackage.ToString() + " have been halted.", null));
}
catch (Exception excp)
{
logger.Error("Exception SIPNotifierClient StartSubscription. " + excp.Message);
}
}
19
Source : SIPRegistrationUserAgent.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
public void StartRegistration()
{
try
{
logger.Debug("Starting SIPRegistrationUserAgent for " + m_sipAccountAOR.ToString() + ".");
while (!m_exit)
{
m_waitForRegistrationMRE.Reset();
m_attempts = 0;
SendInitialRegister();
if (!m_waitForRegistrationMRE.WaitOne(MAX_REGISTRATION_ATTEMPT_TIMEOUT * 1000))
{
m_isRegistered = false;
if (!m_exit && RegistrationTemporaryFailure != null)
{
RegistrationTemporaryFailure(m_sipAccountAOR, "Registration to " + m_registrarHost + " for " + m_sipAccountAOR.ToString() + " timed out.");
}
}
if (!m_exit && m_isRegistered)
{
logger.Debug("SIPRegistrationUserAgent was successful, scheduling next registration to " + m_sipAccountAOR.ToString() + " in " + (m_expiry - REGISTRATION_HEAD_TIME) + "s.");
Thread.Sleep((m_expiry - REGISTRATION_HEAD_TIME) * 1000);
}
else
{
logger.Debug("SIPRegistrationUserAgent temporarily failed, scheduling next registration to " + m_sipAccountAOR.ToString() + " in " + REGISTER_FAILURERETRY_INTERVAL + "s.");
Thread.Sleep(REGISTER_FAILURERETRY_INTERVAL * 1000);
}
}
logger.Debug("SIPRegistrationUserAgent for " + m_sipAccountAOR.ToString() + " stopping.");
}
catch (Exception excp)
{
logger.Error("Exception SIPRegistrationUserAgent Start. " + excp.Message);
}
}
19
Source : RegistryMonitor.cs
with GNU General Public License v3.0
from Dysman
with GNU General Public License v3.0
from Dysman
public void Start()
{
if (_disposed)
throw new ObjectDisposedException(null, "This instance is already disposed");
lock (_threadLock)
{
if (!IsMonitoring)
{
_eventTerminate.Reset();
_thread = new Thread(new ThreadStart(MonitorThread)) { IsBackground = true };
_thread.Start();
}
}
}
19
Source : BufferWithLocks.cs
with GNU General Public License v3.0
from elecyb
with GNU General Public License v3.0
from elecyb
public bool AcquireWriteLock(int millisecondsTimeout = System.Threading.Timeout.Infinite)
{
if (!WriteWaitEvent.WaitOne(millisecondsTimeout))
return false;
ReadWaitEvent.Reset();
return true;
}
19
Source : BufferWithLocks.cs
with GNU General Public License v3.0
from elecyb
with GNU General Public License v3.0
from elecyb
public bool AcquireReadLock(int millisecondsTimeout = System.Threading.Timeout.Infinite)
{
if (!ReadWaitEvent.WaitOne(millisecondsTimeout))
return false;
WriteWaitEvent.Reset();
return true;
}
19
Source : CortexClient.cs
with MIT License
from Emotiv
with MIT License
from Emotiv
private void RetryConnect() {
m_OpenedEvent.Reset();
if (_wSC == null || (_wSC.State != WebSocketState.None && _wSC.State != WebSocketState.Closed))
return;
_wSC.Open();
}
19
Source : CortexClient.cs
with MIT License
from Emotiv
with MIT License
from Emotiv
public void Open()
{
// set timer for connect cortex service
SetWSCTimer();
//Open websocket
m_OpenedEvent.Reset();
if (_wSC == null || (_wSC.State != WebSocketState.None && _wSC.State != WebSocketState.Closed))
return;
_wSC.Open();
}
19
Source : ThriftServer.cs
with Apache License 2.0
from endink
with Apache License 2.0
from endink
public Task StartAsync()
{
lock (_eventLocked)
{
_eventLocked.WaitOne();
_eventLocked.Reset();
}
Guard.ArgumentCondition(this.ServerState != State.Closed, "Thrift server is closed");
if (this.ServerState == State.NotStarted)
{
return this._transport.StartAsync()
.ContinueWith(t =>
{
if (t.Exception != null)
{
_logger.LogError(default(EventId),
t.Exception,
$"Thrift Server startup failed !");
}
else
{
_logger.LogInformation("Thrift Server was started.");
this.ServerState = State.Running;
}
_eventLocked.Set();
});
}
else
{
_logger.LogWarning($"Repeated invocation of the {nameof(ThriftServer)}.{nameof(ThriftServer.StartAsync)} method.");
_eventLocked.Set();
return Task.FromResult(0);
}
}
19
Source : ThriftServer.cs
with Apache License 2.0
from endink
with Apache License 2.0
from endink
public Task CloseAsync(TimeSpan? timeout = null)
{
lock (_eventLocked)
{
_eventLocked.WaitOne();
_eventLocked.Reset();
}
if (this.ServerState == State.Closed)
{
_eventLocked.Set();
return Task.FromResult(0);
}
if (this.ServerState == State.Running)
{
return _transport.StopAsync(timeout).ContinueWith(t =>
{
if (t.Exception != null)
{
_logger.LogError(default(EventId),
t.Exception,
$"Thrift Server stop failed.");
}
else
{
_logger.LogInformation("Thrift Server was stopped.");
this.ServerState = State.Closed;
}
_eventLocked.Set();
});
}
else
{
// Executors are created in the constructor, so we should shut them down here even if the
// server was never actually started
_logger.LogWarning($"Thrift server was never actually started ( {nameof(ThriftServer)}.{nameof(ThriftServer.CloseAsync)} method ).");
this.ServerState = State.Closed;
_eventLocked.Set();
return Task.FromResult(0);
}
}
19
Source : LegacyThreadingData.cs
with MIT License
from enricosada
with MIT License
from enricosada
internal void SignalLegacyThreadStart(RequestBuilder instance)
{
ErrorUtilities.VerifyThrow
(
instance != null &&
instance.RequestEntry != null &&
instance.RequestEntry.Request != null,
"Cannot signal legacy thread start for a RequestBuilder without a request"
);
int submissionId = instance.RequestEntry.Request.SubmissionId;
this.InstanceForMainThread = instance;
Tuple<AutoResetEvent, ManualResetEvent> legacyThreadingEvents = null;
lock (_legacyThreadingEventsLock)
{
_legacyThreadingEventsById.TryGetValue(submissionId, out legacyThreadingEvents);
}
ErrorUtilities.VerifyThrow(legacyThreadingEvents != null, "We're trying to signal that the legacy thread is ready for submission {0} to execute, but that submission has not been registered", submissionId);
// signal that this submission is currently controlling the legacy thread
legacyThreadingEvents.Item1.Set();
// signal that the legacy thread is not currently idle
legacyThreadingEvents.Item2.Reset();
}
19
Source : NodeProviderOutOfProcTaskHost.cs
with MIT License
from enricosada
with MIT License
from enricosada
internal bool CreateNode(TaskHostContext hostContext, INodePacketFactory factory, INodePacketHandler handler, TaskHostConfiguration configuration)
{
ErrorUtilities.VerifyThrowArgumentNull(factory, "factory");
ErrorUtilities.VerifyThrow(!_nodeIdToPacketFactory.ContainsKey((int)hostContext), "We should not already have a factory for this context! Did we forget to call DisconnectFromHost somewhere?");
if (AvailableNodes == 0)
{
ErrorUtilities.ThrowInternalError("All allowable nodes already created ({0}).", _nodeContexts.Count);
return false;
}
// Start the new process. We preplaced in a node mode with a node number of 2, to indicate that we
// want to start up an MSBuild task host node.
string commandLineArgs = " /nologo /nodemode:2 ";
string msbuildLocation = GetMSBuildLocationFromHostContext(hostContext);
// we couldn't even figure out the location we're trying to launch ... just go ahead and fail.
if (msbuildLocation == null)
{
return false;
}
CommunicationsUtilities.Trace("For a host context of {0}, spawning executable from {1}.", hostContext.ToString(), msbuildLocation ?? "MSBuild.exe");
// Make it here.
NodeContext context = GetNode
(
msbuildLocation,
commandLineArgs,
(int)hostContext,
this,
CommunicationsUtilities.GetTaskHostHostHandshake(hostContext),
CommunicationsUtilities.GetTaskHostClientHandshake(hostContext),
NodeContextTerminated
);
if (null != context)
{
_nodeContexts[hostContext] = context;
// Start the asynchronous read.
context.BeginAsyncPacketRead();
_activeNodes.Add((int)hostContext);
_noNodesActiveEvent.Reset();
return true;
}
return false;
}
19
Source : DualQueue.cs
with MIT License
from enricosada
with MIT License
from enricosada
internal void Enqueue(T item)
{
lock (queueLock)
{
// queue the event
queue.Enqueue(item);
writingQueueCount++;
// if the queue transitions from empty to non-empty reset the queue empty event and raise queue ready event
if ( writingQueueCount == 1)
{
// raise the event saying queue contains data
queueReadyEvent.Set();
// reset queue empty
if (queueEmptyEvent != null)
{
queueEmptyEvent.Reset();
}
}
}
}
19
Source : DualQueue.cs
with MIT License
from enricosada
with MIT License
from enricosada
internal void EnqueueArray(T[] items)
{
lock (queueLock)
{
// queue the event
foreach (T item in items)
{
queue.Enqueue(item);
}
writingQueueCount += items.Length;
// if the queue transitions from empty to non-empty reset the queue empty event
if (writingQueueCount == items.Length)
{
// raise the event saying queue contains data
queueReadyEvent.Set();
// reset queue empty
if (queueEmptyEvent != null)
{
queueEmptyEvent.Reset();
}
}
}
}
19
Source : DualQueue.cs
with MIT License
from enricosada
with MIT License
from enricosada
internal void Clear()
{
lock (queueLock)
{
backingQueueA.Clear();
backingQueueB.Clear();
writingQueueCount = 0;
// reset queue ready event because the queue is now empty
queueReadyEvent.Reset();
// raise queue empty event because the queue is now empty
if (queueEmptyEvent != null)
{
queueEmptyEvent.Set();
}
}
}
19
Source : DualQueue.cs
with MIT License
from enricosada
with MIT License
from enricosada
private T GetTopItem(bool dequeue)
{
Queue<T> readingQueue = GetReadingQueue();
T item = default(T);
if (readingQueue.Count > 0)
{
item = dequeue ? readingQueue.Dequeue() : readingQueue.Peek();
}
// if the reading queue is now empty
if (readingQueue.Count == 0)
{
// wait until the current writer (if any) is done with the posting queue
lock (queueLock)
{
// confirm both queues are now empty -- this check is important because
// a writer may have added to the queue while we were waiting for a lock
if ((backingQueueA.Count == 0) && (backingQueueB.Count == 0))
{
// signal there are no more items to read
queueReadyEvent.Reset();
if (queueEmptyEvent != null)
{
queueEmptyEvent.Set();
}
}
}
}
return item;
}
19
Source : NodeWorkerThread.cs
with MIT License
from enricosada
with MIT License
from enricosada
private void NodeActionLoop(NodeLoopExecutionMode executionMode, int nodeProxyId, BuildResult [] requestResults)
{
// Create an array of event to the node thread responds
WaitHandle[] waitHandles = GetHandlesArray(executionMode);
int resultCount = 0;
// A thread that is waiting for a done notification is no longer
// actively executing a task so the active cound needs to be decreased
if (executionMode != NodeLoopExecutionMode.BaseActiveThread)
{
Interlocked.Decrement(ref activeThreadCount);
threadCountEvent.Set();
}
bool continueExecution = true;
while (continueExecution)
{
int eventType = WaitHandle.WaitAny(waitHandles);
if (Environment.GetEnvironmentVariable("MSBUILDDEBUG") == "1")
{
Console.WriteLine("NodeProxy :" + nodeProxyId + " waking up due " + eventType);
}
// Node exit event - all threads need to exit
if (eventType == 0)
{
continueExecution = false;
}
// New work item has appeared in the queue
else if (eventType == 1 && executionMode != NodeLoopExecutionMode.WaitingPreplacediveThread )
{
ErrorUtilities.VerifyThrow(
executionMode == NodeLoopExecutionMode.WaitingActiveThread ||
executionMode == NodeLoopExecutionMode.BaseActiveThread,
"Only active threads should receive work item events");
if (executionMode == NodeLoopExecutionMode.BaseActiveThread)
{
TaskExecutionState taskToExecute = null;
lock (workItemQueue)
{
taskToExecute = workItemQueue.Dequeue();
// We may get a single event for multiple messages so only reset the event
// if the queue is empty
if (workItemQueue.Count == 0)
{
workItemInsertionEvent.Reset();
}
}
// Execute the task either directly or on a child thread
ErrorUtilities.VerifyThrow(taskToExecute != null, "Expected a workitem");
// Wait until all there are no other active threads, we
// always transition from 0 to 1 atomically before executing the task
while (Interlocked.CompareExchange(ref activeThreadCount, 1, 0) != 0)
{
threadCountEvent.WaitOne();
threadCountEvent.Reset();
}
proxyIdToWorkerThread[taskToExecute.NodeProxyId] = this;
// Actually execute the task
taskToExecute.ExecuteTask();
proxyIdToWorkerThread.Remove(taskToExecute.NodeProxyId);
// Indicate that this thread is no longer active
Interlocked.Decrement(ref activeThreadCount);
threadCountEvent.Set();
}
else
{
// Change the thread execution mode since it will no longer be
// listening to the work item queue
executionMode = NodeLoopExecutionMode.WaitingPreplacediveThread;
threadActive = false;
waitHandles = GetHandlesArray(executionMode);
TaskWorkerThread workerThread = null;
lock (workerThreadQueue)
{
if (workerThreadQueue.Count != 0)
{
//Console.WriteLine("REUSING a thread");
workerThread = workerThreadQueue.Dequeue();
}
}
if (workerThread == null)
{
//Console.WriteLine("CREATING a thread");
workerThread = new TaskWorkerThread();
}
workerThread.ActivateThread();
}
}
else if (eventType == 1 && executionMode == NodeLoopExecutionMode.WaitingPreplacediveThread ||
eventType == 2 && executionMode == NodeLoopExecutionMode.WaitingActiveThread)
{
// There maybe multiple results in the list so we need to loop over it
// and store the results
int originalResultCount = resultCount;
lock (targetEvaluationResults)
{
//Console.WriteLine("Worker thread for: " + nodeProxyId + " Got results");
LinkedListNode<BuildResult> currentNode = targetEvaluationResults.First;
while (currentNode != null)
{
BuildResult buildResult = currentNode.Value;
ErrorUtilities.VerifyThrow(
buildResult.RequestId < requestResults.Length,
"The request ids should be inside the array");
requestResults[buildResult.RequestId] = buildResult;
// Increment the result count to indicate that we got another result
resultCount++;
// Go to the next entry in the list (most of the time there will be just one entry)
currentNode = currentNode.Next;
}
targetEvaluationResults.Clear();
// Reset the handle now that we done with the events
int handleIndex = executionMode == NodeLoopExecutionMode.WaitingPreplacediveThread ? 1 : 2;
((ManualResetEvent)waitHandles[handleIndex]).Reset();
}
ErrorUtilities.VerifyThrow(originalResultCount < resultCount, "We should have found at least 1 result");
// If we received results for all the requests we need to exit
if (resultCount == requestResults.Length)
{
continueExecution = false;
}
}
// Check if we need to update the state
if (executionMode == NodeLoopExecutionMode.BaseActiveThread && !threadActive)
{
continueExecution = false;
}
}
ErrorUtilities.VerifyThrow
(resultCount == 0 || executionMode != NodeLoopExecutionMode.BaseActiveThread,
"The base thread should never return a value");
// If a thread exits this loop it is back to actively executing the task,
// so the active thread count has to be increased
if (executionMode != NodeLoopExecutionMode.BaseActiveThread)
{
while (Interlocked.CompareExchange(ref activeThreadCount, 1, 0) != 0)
{
threadCountEvent.WaitOne();
threadCountEvent.Reset();
}
}
}
19
Source : TaskExecutionModule.cs
with MIT License
from enricosada
with MIT License
from enricosada
internal void Shutdown()
{
if (moduleMode != TaskExecutionModuleMode.SingleProcMode)
{
workerThread.Shutdown();
while (overallThreadCount != 0)
{
threadOverallCountEvent.WaitOne();
threadOverallCountEvent.Reset();
}
if (profileExecution)
{
int taskTimeMs = 0;
if (totalTaskTime != 0)
{
TimeSpan taskTimeSpan = new TimeSpan(totalTaskTime);
taskTimeMs = (int)taskTimeSpan.TotalMilliseconds;
}
Console.WriteLine("Node time spent " + taskTimeMs);
}
}
}
19
Source : TaskExecutionModule.cs
with MIT License
from enricosada
with MIT License
from enricosada
internal void WaitForZeroActiveThreadCount()
{
while (Interlocked.CompareExchange(ref activeThreadCount, 1, 0) != 0)
{
threadActiveCountEvent.WaitOne();
threadActiveCountEvent.Reset();
}
lastTaskActivity = DateTime.Now.Ticks;
}
19
Source : TaskWorkerThread.cs
with MIT License
from enricosada
with MIT License
from enricosada
private void NodeActionLoop
(
NodeLoopExecutionMode executionMode,
int handleId,
BuildResult [] buildResults
)
{
// Create an array of event to the node thread responds
WaitHandle[] waitHandles = GetHandlesArray(executionMode);
int resultCount = 0;
long entryTime = 0;
// A thread that is waiting for a done notification is no longer
// actively executing a task so the active cound needs to be decreased
if (executionMode != NodeLoopExecutionMode.BaseActiveThread)
{
parentModule.DecrementActiveThreadCount();
// If requested measure the time spent waiting for the results
if (profileExecution)
{
entryTime = DateTime.Now.Ticks;
}
}
bool continueExecution = true;
while (continueExecution)
{
int eventType;
// Try and avoid the wait on kernel objects if possible.
if (!WaitAnyFast(executionMode, out eventType))
{
eventType = WaitHandle.WaitAny(waitHandles);
}
if (Engine.debugMode)
{
Console.WriteLine("TaskWorkerThread: HandleId " + handleId + " waking up due to event type " + eventType);
}
// Node exit event - all threads need to exit
if (eventType == 0)
{
continueExecution = false;
}
// New work item has appeared in the queue
else if (eventType == 1 && executionMode != NodeLoopExecutionMode.WaitingPreplacediveThread )
{
ErrorUtilities.VerifyThrow(
executionMode == NodeLoopExecutionMode.WaitingActiveThread ||
executionMode == NodeLoopExecutionMode.BaseActiveThread,
"Only active threads should receive work item events");
if (executionMode == NodeLoopExecutionMode.BaseActiveThread)
{
// Wait until all there are no other active threads, we
// always transition from 0 to 1 atomically before executing the task
parentModule.WaitForZeroActiveThreadCount();
TaskExecutionState taskToExecute = null;
lock (workItemQueue)
{
taskToExecute = workItemQueue.Dequeue();
// We may get a single event for multiple messages so only reset the event
// if the queue is empty
if (workItemQueue.Count == 0)
{
workItemInsertionEvent.Reset();
}
}
// Execute the task either directly or on a child thread
ErrorUtilities.VerifyThrow(taskToExecute != null, "Expected a workitem");
handleIdToWorkerThread[taskToExecute.HandleId] = this;
currentWorkitem = taskToExecute;
// Actually execute the task (never throws - all exceptions are captured)
taskToExecute.ExecuteTask();
currentWorkitem = null;
handleIdToWorkerThread.Remove(taskToExecute.HandleId);
// Indicate that this thread is no longer active
parentModule.DecrementActiveThreadCount();
}
else
{
// Change the thread execution mode since it will no longer be
// listening to the work item queue
executionMode = NodeLoopExecutionMode.WaitingPreplacediveThread;
threadActive = false;
waitHandles = GetHandlesArray(executionMode);
TaskWorkerThread workerThread = null;
lock (workerThreadQueue)
{
if (workerThreadQueue.Count != 0)
{
//Console.WriteLine("REUSING a thread");
workerThread = workerThreadQueue.Dequeue();
}
}
if (workerThread == null)
{
//Console.WriteLine("CREATING a thread");
workerThread = new TaskWorkerThread(parentModule, exitTaskThreads, exitTaskThreadsCache, workerThreadQueue, handleIdToWorkerThread,
workItemQueue, workItemInsertionEvent, waitingTasks, profileExecution);
}
workerThread.ActivateThread();
}
}
else if (eventType == 1 && executionMode == NodeLoopExecutionMode.WaitingPreplacediveThread ||
eventType == 2 && executionMode == NodeLoopExecutionMode.WaitingActiveThread)
{
// There maybe multiple results in the list so we need to loop over it
// and store the results
int originalResultCount = resultCount;
lock (postedBuildResults)
{
LinkedListNode<BuildResult> currentNode = postedBuildResults.First;
while (currentNode != null)
{
BuildResult buildResult = currentNode.Value;
ErrorUtilities.VerifyThrow(
buildResult.RequestId < buildResults.Length,
"The request ids should be inside the array");
buildResults[buildResult.RequestId] = buildResult;
// Increment the result count to indicate that we got another result
resultCount++;
// Go to the next entry in the list (most of the time there will be just one entry)
currentNode = currentNode.Next;
}
postedBuildResults.Clear();
// Reset the handle now that we done with the events
int handleIndex = executionMode == NodeLoopExecutionMode.WaitingPreplacediveThread ? 1 : 2;
((ManualResetEvent)waitHandles[handleIndex]).Reset();
}
ErrorUtilities.VerifyThrow(originalResultCount < resultCount, "We should have found at least 1 result");
// If we received results for all the requests we need to exit
if (resultCount == buildResults.Length)
{
continueExecution = false;
}
}
// Check if we need to update the state
if (executionMode == NodeLoopExecutionMode.BaseActiveThread && !threadActive)
{
continueExecution = false;
}
}
ErrorUtilities.VerifyThrow
(resultCount == 0 || executionMode != NodeLoopExecutionMode.BaseActiveThread,
"The base thread should never return a value");
// If a thread exits this loop it is back to actively executing the task,
// so the active thread count has to be increased
if (executionMode != NodeLoopExecutionMode.BaseActiveThread)
{
parentModule.WaitForZeroActiveThreadCount();
// Sent the time spent waiting for results to the ExecutionState so that the task execution time can be measured correctly
if (profileExecution)
{
this.currentWorkitem.NotifyOfWait(entryTime);
}
}
}
See More Examples