// Execute forever public void Execute() { while (stopped == false) { // Internal events first if (internalEventsHead != null) { Internal internalEvent = internalEventsHead; internalEventsHead = internalEvent.next; #if DEBUG_TCP Core.Log("Dispatching Internal Event at " + DateTime.UtcNow.ToString() + " calling '" + internalEvent.fun.ToString() + "'."); #endif internalEvent.fun(internalEvent.arg); continue; } // One read of NOW ulong now = (ulong)DateTime.UtcNow.Ticks; // Deal with timers TimeSpan waitTime = TimeSpan.MaxValue; lock (timers) { Timer timer = (Timer)timers.Advance(now); if (timer != null) { // This timer has expired; service // it immediately and start over #if DEBUG_TCP Core.Log("Timer Expiration at " + (new DateTime((long)now)).ToString() + " calling '" + timer.fun.ToString() + "'."); #endif timer.fun(timer.arg); continue; } timer = (Timer)timers.GetSoonest(); if (timer != null) { ulong soonest = timer.time; if (soonest < now) { Core.Log("Negative WaitTime"); waitTime = new TimeSpan(0L); } else { waitTime = new TimeSpan((long)(soonest - now)); } } } // Grab a copy of the external-event pointers so // we're not affected by changes to them on other // threads Callback[] funs = eFuns; CallbackArgs[] args = eArgs; WaitHandle[] handles = eHandles; // Shuffle the array values so the same tasks aren't // always preferred to others (WaitAny() will unblock // against the lowest-index WaitHandle in the array) lock (handles.SyncRoot) { int n = handles.Length; for (int i = 0; i < n - 1; ++i) { // Swap the current element of the list with // an entry that follow it. Instead of an // expensive real random-number generator, // generate a pseudo-random number by multiplying // a largish prime with an increasing count uint swapWith = (uint)(i + ((unchecked (53533511 * swapCount++)) % (n - i))); if (swapWith != i) { Callback swapFun = funs[swapWith]; CallbackArgs swapArgs = args[swapWith]; WaitHandle swapHandle = handles[swapWith]; funs[swapWith] = funs[i]; args[swapWith] = args[i]; handles[swapWith] = handles[i]; funs[i] = swapFun; args[i] = swapArgs; handles[i] = swapHandle; } } } int rc = WaitHandle.WaitAny(handles, waitTime); if (rc == WaitHandle.WaitTimeout) { continue; } if (rc < 0 || rc >= handles.Length) { throw new ApplicationException("Invalid WaitAny"); } Callback cb = funs[rc]; if (cb != null) { NetStatus res = cb(args[rc]); if (!NetStatus.SUCCEEDED(res)) { Core.Panic("Error handling internal event."); } } } Core.Log("NetStack dispatcher exiting...\n"); }
protected override void DoProtocol() { Packet[] buffer = new Packet[_MAX_SEQ + 1]; /* buffers for the outbound stream */ byte ackExpected = 0; /* oldest frame as yet unacknowledged */ byte nextFrameToSend = 0; /* MAX SEQ > 1; used for outbound stream */ byte frameExpected = 0; /* next frame expected on inbound stream */ byte nbBuffered = 0; /* number of output buffers currently in use */ // Creates events that trigger the thread changing var waitHandles = new WaitHandle[] { _closingEvents[_actorType], _networkLayerReadyEvents[_actorType], _frameArrivalEvents[_actorType], _frameErrorEvents[_actorType], _frameTimeoutEvents[_actorType] }; /* allow network layer ready events */ EnableNetworkLayer(); var running = true; while (running) { // Wait trigger events to activate the thread action var index = WaitHandle.WaitAny(waitHandles); // Execute the task related to the event raised switch (index) { case _STOP_RUNNING: // Received the closing event (_closingEvent) running = false; break; case _NETWORK_LAYER_READY: // The network layer has a packet to send (_networkLayerReadyEvent) // In our case, a new packet read from the input file // Accept, save, and transmit a new frame. // Fetch new packet nbBuffered++; /* expand the sender’s window */ if (nbBuffered < _MAX_SEQ) { EnableNetworkLayer(); } else { DisableNetworkLayer(); } buffer[nextFrameToSend] = FromNetworkLayer(); SendData(nextFrameToSend, frameExpected, buffer); /* transmit the frame */ nextFrameToSend = Inc(nextFrameToSend); /* advance sender’s upper window edge */ break; case _FRAME_ARRIVAL: // A data or control frame has arrived (_frameArrivalEvent) // In our case, a new packet to write to the output file or received an ack // get incoming frame from physical layer //var r = FromPhysicalLayer(); /* scratch variable */ var a = FromPhysicalLayer(); /* scratch variable */ //Decode frame and correct errors using Hamming protocol var r = Hamming.decodeHamming(a); if (r == null) { // _frameErrorEvents[(byte)(1 - _threadId)].Set(); break; //reject frame } if (r.Seq == frameExpected) { // Frames are accepted only in order. ToNetworkLayer(r.Info); /* pass packet to network layer */ frameExpected = Inc(frameExpected); /* advance lower edge of receiver’s window */ } // Ack n implies n − 1, n − 2, etc.Check for this. while (Between(ackExpected, r.Ack, nextFrameToSend)) { // Handle piggybacked ack. nbBuffered--; /* one frame fewer buffered */ StopTimer(ackExpected); /* frame arrived intact; stop timer */ ackExpected = Inc(ackExpected); /* contract sender’s window */ } break; case _CKSUM_ERROR: // Just ignore bad frames (_frameErrorEvent) break; case _TIMEOUT: // Trouble; retransmit all outstanding frames (_frameTimeoutEvent) nextFrameToSend = ackExpected; /* start retransmitting here */ for (byte i = 1; i <= nbBuffered; i++) { SendData(nextFrameToSend, frameExpected, buffer); /* resend frame */ nextFrameToSend = Inc(nextFrameToSend); /* prepare to send the next one */ } break; } if (nbBuffered < _MAX_SEQ) { EnableNetworkLayer(); } else { DisableNetworkLayer(); } } Console.WriteLine(string.Format("**** The Data Link Layer of the {0} thread terminated ****", _actorType)); }
// 新启动一个线程的SendAndRecv public int SendAndRecv(byte[] baSend, out byte[] baRecv, out int nRecvLength, out string strError) { baRecv = null; nRecvLength = 0; strError = ""; this.eventClose.Reset(); this.eventFinished.Reset(); this.baSend = baSend; this.strErrorString = ""; this.nErrorCode = 0; Thread clientThread = new Thread(new ThreadStart(SendAndRecvThread)); clientThread.Start(); // 等待线程结束 WaitHandle[] events = new WaitHandle[2]; events[0] = this.eventClose; events[1] = this.eventFinished; int nIdleTimeCount = 0; int nIdleTicks = 100; REDO: DoIdle(); int index = 0; try { index = WaitHandle.WaitAny(events, nIdleTicks, false); } catch (System.Threading.ThreadAbortException ex) { strError = "线程被杀死"; goto ERROR1; } if (index == WaitHandle.WaitTimeout) { nIdleTimeCount += nIdleTicks; if (nIdleTicks >= this.Timeout) { // 超时 strError = "超时 (" + this.Timeout + "毫秒)"; return(-1); } goto REDO; } else if (index == 0) { // 得到Close信号 strError = "通道被切断"; goto ERROR1; } else { // 得到finish信号 if (nErrorCode != 0) { if (nErrorCode == -1) { this.CloseSocket(); } strError = this.strErrorString; return(nErrorCode); } baRecv = this.baRecv; nRecvLength = baRecv.Length; return(0); } ERROR1: this.CloseSocket(); return(-1); }
public static int ReadEx(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellation = default(CancellationToken)) { if (stream == null) { throw new ArgumentNullException("stream"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count <= 0 || count > buffer.Length) { throw new ArgumentOutOfRangeException("count"); //Disallow 0 as a debugging aid. } if (offset > buffer.Length - count) { throw new ArgumentOutOfRangeException("count"); } int totalReadCount = 0; while (totalReadCount < count) { cancellation.ThrowIfCancellationRequested(); int currentReadCount; //Big performance problem with BeginRead for other stream types than NetworkStream. //Only take the slow path if cancellation is possible. if (stream is NetworkStream && cancellation.CanBeCanceled) { var ar = stream.BeginRead(buffer, offset + totalReadCount, count - totalReadCount, null, null); if (!ar.CompletedSynchronously) { WaitHandle.WaitAny(new WaitHandle[] { ar.AsyncWaitHandle, cancellation.WaitHandle }, -1); } //EndRead might block, so we need to test cancellation before calling it. //This also is a bug because calling EndRead after BeginRead is contractually required. //A potential fix is to use the ReadAsync API. Another fix is to register a callback with BeginRead that calls EndRead in all cases. cancellation.ThrowIfCancellationRequested(); currentReadCount = stream.EndRead(ar); } else { //IO interruption not supported in this path. currentReadCount = stream.Read(buffer, offset + totalReadCount, count - totalReadCount); } if (currentReadCount == 0) { return(0); } totalReadCount += currentReadCount; } return(totalReadCount); }
private void threadCSVValues(object type) { Errors errRes = Errors.NoError; Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = ProgramBase.ss_MainCultureInfo; //new System.Globalization.CultureInfo(@"en-US") //Определить тип загружаемых значений CONN_SETT_TYPE typeValues = (CONN_SETT_TYPE)type; int indxEv = -1 , prevIndxTECComponents = indxTECComponents; string strPBRNumber = string.Empty; // ...только для ПБР if (typeValues == CONN_SETT_TYPE.PBR) {//Только для ПБР //Противоположные операции при завершении потока 'threadPPBRCSVValues' //Разрешить запись ПБР-значений if (m_markSavedValues.IsMarked((int)INDEX_MARK_PPBRVALUES.PBR_ENABLED) == true) { m_markSavedValues.Marked((int)INDEX_MARK_PPBRVALUES.PBR_AVALIABLE); } else { ; } //Запретить запись Админ-значений if (m_markSavedValues.IsMarked((int)INDEX_MARK_PPBRVALUES.ADMIN_ENABLED) == true) { m_markSavedValues.UnMarked((int)INDEX_MARK_PPBRVALUES.ADMIN_AVALIABLE); } else { ; } strPBRNumber = getNamePBRNumber((int)GetPropertiesOfNameFilePPBRCSVValues()[1]); } else { ; } //Снять все признаки причин прекращения выполнения обработки событий for (INDEX_WAITHANDLE_REASON i = INDEX_WAITHANDLE_REASON.ERROR; i < (INDEX_WAITHANDLE_REASON.ERROR + 1); i++) { ((ManualResetEvent)m_waitHandleState[(int)i]).Reset(); } foreach (TECComponent comp in allTECComponents) { if (comp.IsGTP == true) //Является ГТП { indxEv = WaitHandle.WaitAny(m_waitHandleState); if (indxEv == 0) { switch (typeValues) { case CONN_SETT_TYPE.ADMIN: errRes = saveCSVValues(allTECComponents.IndexOf(comp), typeValues); break; case CONN_SETT_TYPE.PBR: errRes = saveCSVValues(allTECComponents.IndexOf(comp), strPBRNumber); break; default: break; } //if (! (errRes == Errors.NoError)) // ; //Ошибка ??? //else // ; } else { //Ошибка ??? //break; //completeHandleStates(); ; } } else { ; } } //Очистить таблицу, полученную из CSV-файла m_tableValuesResponse.Clear(); m_tableValuesResponse = null; if (typeValues == CONN_SETT_TYPE.PBR) {//Только для ПБР //Противоположные операции в 'ImpPPBRCSVValuesRequest' //Запретить запись ПБР-значений // , запрет устанавливается автоматически //Разрешить запись Админ-значений if (m_markSavedValues.IsMarked((int)INDEX_MARK_PPBRVALUES.ADMIN_ENABLED) == true) { m_markSavedValues.Marked((int)INDEX_MARK_PPBRVALUES.ADMIN_AVALIABLE); } else { ; } } else { ; } //Обновить значения на вкладке GetRDGValues(/*m_typeFields,*/ prevIndxTECComponents); }
private void WorkItemPumpingThreadEntry() { MailboxSearchWorkItem workItem = null; ExWatson.SendReportOnUnhandledException(delegate() { WaitHandle[] waitHandles = new WaitHandle[] { this.shutdownEvent, this.queueSemaphore }; WaitHandle[] waitHandles2 = new WaitHandle[] { this.shutdownEvent, this.workItemSemaphore }; while (WaitHandle.WaitAny(waitHandles) != 0) { if (WaitHandle.WaitAny(waitHandles2) == 0) { MailboxSearchServer.Tracer.TraceDebug <ExDateTime>((long)this.GetHashCode(), "WorkItemPumpingThread received shutdown signal when waiting for work item resource, exiting at {0}", ExDateTime.Now); return; } workItem = this.GetNextWorkItem(); if (workItem != null) { bool releaseSemaphore = !workItem.IsCompleted; try { GrayException.MapAndReportGrayExceptions(delegate() { bool flag = true; try { lock (this) { switch (workItem.Action) { case WorkItemAction.Start: workItem.Start(); break; case WorkItemAction.Remove: workItem.Remove(); break; } flag = workItem.IsCompleted; } } finally { if (flag) { this.RemoveWorkItem(workItem.SearchId, releaseSemaphore, workItem.IsEstimateOnly); } } }); } catch (GrayException ex) { MailboxSearchServer.Tracer.TraceError <SearchId, Exception>((long)this.GetHashCode(), "WorkItem {0} has unhandled exception {1}, the work item is discarded!", workItem.SearchId, ex); SearchEventLogger.Instance.LogDiscoverySearchServerErrorEvent("An unhandled exception occurred while processing the work item, ignoring and continuing the processing of queue", workItem.SearchId.SearchName, workItem.SearchId.MailboxDsName, ex); } } } MailboxSearchServer.Tracer.TraceDebug <ExDateTime>((long)this.GetHashCode(), "WorkItemPumpingThread received shutdown signal when waiting for Queue, exiting at {0}", ExDateTime.Now); }, delegate(object exception) { MailboxSearchServer.Tracer.TraceError((long)this.GetHashCode(), "ExWatsonWrappedCall: Unhandled exception {0}", new object[] { exception }); SearchEventLogger.Instance.LogDiscoverySearchServerErrorEvent("ExWatsonWrappedCall: Unhandled exception", (workItem != null) ? workItem.SearchId.SearchName : null, (workItem != null) ? workItem.SearchId.MailboxDsName : null, exception.ToString()); return(!(exception is GrayException)); }); }
internal static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { return(WaitHandle.WaitAny(waitHandles, millisecondsTimeout)); }
/// <summary> /// Main function of the parsing thread. /// This function waits on the queue of the parsing requests and build /// the parsing tree for a specific file. The resulting tree is built /// using LibraryNode objects so that it can be used inside the class /// view or object browser. /// </summary> void ParseThread() { const int waitTimeout = 500; // Define the array of events this function is interest in. // WaitHandle[] eventsToWait = new WaitHandle[] { _requestPresent, _shutDownStarted }; // Execute the tasks. // while (true) { // Wait for a task or a shutdown request. // int waitResult = WaitHandle.WaitAny(eventsToWait, waitTimeout, false); if (1 == waitResult) { // The shutdown of this component is started, so exit the thread. return; } LibraryTask task = null; lock (_requests) { if (_requests.Count != 0) { task = _requests.Dequeue(); } if (_requests.Count == 0) { _requestPresent.Reset(); } } if (null == task) { continue; } ScopeNode scope = null; if (task.Text == null) { if (File.Exists(task.FileName)) { Debug.WriteLine("Parse request (no text): " + task.FileName + " " + task.ModuleID); return; } } else { Debug.WriteLine("Parse request: " + task.FileName + " " + task.ModuleID); return; } LibraryNode module = new LibraryNode( Path.GetFileName(task.FileName), LibraryNode.LibraryNodeType.PhysicalContainer); CreateModuleTree(module, module, scope, "", task.ModuleID); if (task.ModuleID != null) { LibraryNode previousItem; lock (_files) if (_files.TryGetValue(task.ModuleID, out previousItem)) { _files.Remove(task.ModuleID); } _library.RemoveNode(previousItem); } _library.AddNode(module); if (task.ModuleID != null) { lock (_files) _files.Add(task.ModuleID, module); } } }
public async Task HostLifetimeOnStartedCanBeCancelled() { var serviceStarting = new ManualResetEvent(false); var lifetimeStart = new ManualResetEvent(false); var lifetimeContinue = new ManualResetEvent(false); FakeHostedService service; FakeHostLifetime lifetime; using (var host = CreateBuilder() .ConfigureServices((services) => { services.AddSingleton <IHostedService>(_ => new FakeHostedService() { StartAction = ct => { serviceStarting.Set(); } }); services.AddSingleton <IHostLifetime>(_ => new FakeHostLifetime() { StartAction = ct => { lifetimeStart.Set(); WaitHandle.WaitAny(new[] { lifetimeContinue, ct.WaitHandle }); } }); }) .Build()) { var cts = new CancellationTokenSource(); var startTask = Task.Run(() => host.StartAsync(cts.Token)); Assert.True(lifetimeStart.WaitOne(TimeSpan.FromSeconds(5))); Assert.False(serviceStarting.WaitOne(0)); cts.Cancel(); await Assert.ThrowsAsync <OperationCanceledException>(() => startTask); Assert.False(serviceStarting.WaitOne(0)); lifetimeContinue.Set(); Assert.False(serviceStarting.WaitOne(0)); Assert.NotNull(host); service = (FakeHostedService)host.Services.GetRequiredService <IHostedService>(); Assert.Equal(0, service.StartCount); Assert.Equal(0, service.StopCount); Assert.Equal(0, service.DisposeCount); lifetime = (FakeHostLifetime)host.Services.GetRequiredService <IHostLifetime>(); Assert.Equal(1, lifetime.StartCount); Assert.Equal(0, lifetime.StopCount); } Assert.Equal(0, service.StartCount); Assert.Equal(0, service.StopCount); Assert.Equal(1, service.DisposeCount); Assert.Equal(1, lifetime.StartCount); Assert.Equal(0, lifetime.StopCount); }
private static void ControlHttp() { try { WaitHandle[] Handles = new WaitHandle[] { updateLeds, updateAlarm }; while (true) { try { switch (WaitHandle.WaitAny(Handles, 1000)) { case 0: // Update LEDS int i; lock (synchObject) { i = lastLedMask; } HttpUtilities.Get("http://*****:*****@192.168.0.23/ws/?op=SetDigitalOutputs&Values=" + i.ToString()); break; case 1: // Update Alarm bool b; lock (synchObject) { b = lastAlarm.Value; } HttpUtilities.Get("http://*****:*****@192.168.0.23/ws/?op=SetAlarmOutput&Value=" + (b ? "true" : "false")); if (b) { Thread T = new Thread(SendAlarmMail); T.Priority = ThreadPriority.BelowNormal; T.Name = "SendAlarmMail"; T.Start(); } break; default: // Timeout CheckSubscriptions(30); break; } } catch (ThreadAbortException) { // Don't log. Exception will be automatically re-raised. } catch (Exception ex) { Log.Exception(ex); } } } catch (ThreadAbortException) { Thread.ResetAbort(); } catch (Exception ex) { Log.Exception(ex); } }
private void WorkerMethod() { // Doing this so TaskScheduler.FromCurrentSynchronizationContext() will work SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); // Since _tearDown gets called after dispose, there's a slight chance that the underlying object could get garbage collected, so store local copies of these // two delegates up front TickDelegate tick = _tick; TearDownDelegate tearDown = _tearDown; // Let the client create an object from this thread T prepResults = default(T); if (_prep != null) { prepResults = _prep(_prepArgs); } #region Set up the timer DateTime lastTick = DateTime.UtcNow; ManualResetEvent tickEvent = new ManualResetEvent(false); System.Timers.Timer timer = new System.Timers.Timer(); //timer.SynchronizingObject //NOTE: I tried to implement ISynchonizeInvoke, but that approach was a mess. I think this approach of creating a thead for the user is way cleaner timer.Interval = this.Interval; timer.Elapsed += delegate { tickEvent.Set(); }; timer.AutoReset = false; if (_isTimerRunning) { timer.Start(); } #endregion WaitHandle[] handles = new WaitHandle[] { _disposeEvent, _timerSettingsChanged, tickEvent }; while (true) { // Hang this thread until something happens int handleIndex = WaitHandle.WaitAny(handles); if (handleIndex == 0) // I would prefer a switch statement, but there is no Exit While statement { // Dispose was called, this thread needs to finish //_disposeEvent.Reset(); // just leave this one tripped so that break; } else if (handleIndex == 1) { #region Timer settings changed _timerSettingsChanged.Reset(); // Settings for the timer have changed timer.Interval = this.Interval; if (_isTimerRunning) { timer.Start(); // it appears to be safe to call this even when started } else { timer.Stop(); // and to call this again when stopped } #endregion } else if (handleIndex == 2) { #region Timer ticked DateTime currentTick = DateTime.UtcNow; double elapsed = (currentTick - lastTick).TotalMilliseconds; lastTick = currentTick; tickEvent.Reset(); if (_isTimerRunning) { timer.Start(); if (tick != null) // putting this inside the _isTimerRunning, because they may have wanted the timer stopped between ticks, so in that case, just ignore this tick event { tick(prepResults, elapsed); } } #endregion } else { throw new ApplicationException("Unknown wait handle: " + handleIndex.ToString()); } } timer.Stop(); timer.Dispose(); if (tearDown != null) { tearDown(prepResults); } }
public void Search(int mode, int toBeSearh, Action <string, int> callBack, Action <int> callBackNotify) { int index = 0; if (mode == 1) { var d = new Data(); d.prepareData(1); AutoResetEvent[] signals = new AutoResetEvent[] { new AutoResetEvent(false), new AutoResetEvent(false), new AutoResetEvent(false) }; var t1 = new Thread(() => { index = d.SearchModeOne(toBeSearh, "Gold", signals[0], (data) => { callBackNotify.Invoke(data); }); }); t1.Start(); var t2 = new Thread(() => { index = d.SearchModeOne(toBeSearh, "Silver", signals[1], (data) => { callBackNotify.Invoke(data); }); }); t2.Start(); var t3 = new Thread(() => { index = d.SearchModeOne(toBeSearh, "Platinum", signals[2], (data) => { callBackNotify.Invoke(data); }); }); t3.Start(); int i = WaitHandle.WaitAny(signals); //Thread.Sleep(250); if (i == 0) { callBack.Invoke("Gold", index); } else if (i == 1) { callBack.Invoke("Silver", index); } else if (i == 2) { callBack.Invoke("Platinum", index); } } else if (mode == 2) { var d = new Data(); d.prepareData(2); new Thread(() => { d.SearchModeTwo(toBeSearh, "Gold", (dataBank, i) => { callBack.Invoke(dataBank, i); }, (data) => { callBackNotify.Invoke(data); }); }).Start(); new Thread(() => { d.SearchModeTwo(toBeSearh, "Silver", (dataBank, i) => { callBack.Invoke(dataBank, i); }, (data) => { callBackNotify.Invoke(data); }); }).Start(); new Thread(() => { d.SearchModeTwo(toBeSearh, "Platinum", (dataBank, i) => { callBack.Invoke(dataBank, i); }, (data) => { callBackNotify.Invoke(data); }); }).Start(); } }
protected void Start(string test) { TargetRuntime runtime; switch (EngineId) { case "MonoDevelop.Debugger.Win32": runtime = Runtime.SystemAssemblyService.GetTargetRuntime("MS.NET"); break; case "Mono.Debugger.Soft": runtime = Runtime.SystemAssemblyService.GetTargetRuntimes() .OfType <MonoTargetRuntime> () .OrderByDescending((o) => { //Attempt to find latest version of Mono registred in IDE and use that for unit tests if (string.IsNullOrWhiteSpace(o.Version) || o.Version == "Unknown") { return(new Version(0, 0, 0, 0)); } int indexOfBeforeDetails = o.Version.IndexOf(" (", StringComparison.Ordinal); if (indexOfBeforeDetails == -1) { return(new Version(0, 0, 0, 0)); } string hopefullyVersion = o.Version.Remove(indexOfBeforeDetails); Version version; if (Version.TryParse(hopefullyVersion, out version)) { return(version); } else { return(new Version(0, 0, 0, 0)); } }).FirstOrDefault(); break; default: runtime = Runtime.SystemAssemblyService.DefaultRuntime; break; } if (runtime == null) { Assert.Ignore("Runtime not found for: {0}", EngineId); return; } Console.WriteLine("Target Runtime: " + runtime.DisplayRuntimeName + " " + runtime.Version); // main/build/tests FilePath path = Path.GetDirectoryName(GetType().Assembly.Location); var exe = Path.Combine(path, "MonoDevelop.Debugger.Tests.TestApp.exe"); var cmd = new DotNetExecutionCommand(); cmd.TargetRuntime = runtime; cmd.Command = exe; cmd.Arguments = test; if (Platform.IsWindows) { var monoRuntime = runtime as MonoTargetRuntime; if (monoRuntime != null) { var psi = new System.Diagnostics.ProcessStartInfo(Path.Combine(monoRuntime.Prefix, "bin", "pdb2mdb.bat"), cmd.Command); psi.UseShellExecute = false; psi.CreateNoWindow = true; System.Diagnostics.Process.Start(psi).WaitForExit(); } } var dsi = engine.CreateDebuggerStartInfo(cmd); var soft = dsi as SoftDebuggerStartInfo; if (soft != null) { var assemblyName = AssemblyName.GetAssemblyName(exe); soft.UserAssemblyNames = new List <AssemblyName> (); soft.UserAssemblyNames.Add(assemblyName); } Session = engine.CreateSession(); var ops = new DebuggerSessionOptions(); ops.ProjectAssembliesOnly = true; ops.EvaluationOptions = EvaluationOptions.DefaultOptions; ops.EvaluationOptions.AllowTargetInvoke = AllowTargetInvokes; ops.EvaluationOptions.EvaluationTimeout = 100000; path = path.ParentDirectory.ParentDirectory.Combine("src", "addins", "MonoDevelop.Debugger", "MonoDevelop.Debugger.Tests.TestApp", test + ".cs").FullPath; SourceFile = TextFile.ReadFile(path); TestName = test; AddBreakpoint("break"); var done = new ManualResetEvent(false); Session.TargetHitBreakpoint += (sender, e) => { Frame = e.Backtrace.GetFrame(0); lastStoppedPosition = Frame.SourceLocation; targetStoppedEvent.Set(); done.Set(); }; Session.TargetExceptionThrown += (sender, e) => { Frame = e.Backtrace.GetFrame(0); for (int i = 0; i < e.Backtrace.FrameCount; i++) { if (!e.Backtrace.GetFrame(i).IsExternalCode) { Frame = e.Backtrace.GetFrame(i); break; } } lastStoppedPosition = Frame.SourceLocation; targetStoppedEvent.Set(); }; Session.TargetStopped += (sender, e) => { Frame = e.Backtrace.GetFrame(0); lastStoppedPosition = Frame.SourceLocation; targetStoppedEvent.Set(); }; var targetExited = new ManualResetEvent(false); Session.TargetExited += delegate { targetExited.Set(); }; Session.Run(dsi, ops); switch (WaitHandle.WaitAny(new WaitHandle[] { done, targetExited }, 30000)) { case 0: //Breakpoint is hit good... run tests now break; case 1: throw new Exception("Test application exited before hitting breakpoint"); default: throw new Exception("Timeout while waiting for initial breakpoint"); } }
/// <summary> /// Thread procedure that is responsible for accepting new clients on the TCP server port. /// </summary> private void PortListenerThread(object State) { int port = (int)State; log.Trace("(Port:{0})", port); try { TcpListener listener = new TcpListener(IPAddress.Any, port); listener.Server.LingerState = new LingerOption(true, 0); listener.Server.NoDelay = true; listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); listener.Start(); portListenerReadyEvent.Set(); AutoResetEvent acceptTaskEvent = new AutoResetEvent(false); bool done = false; while (!done) { log.Debug("Waiting for new client."); Task <TcpClient> acceptTask = listener.AcceptTcpClientAsync(); acceptTask.ContinueWith(t => acceptTaskEvent.Set()); WaitHandle[] handles = new WaitHandle[] { acceptTaskEvent, portListenerThreadShutdownEvent }; int index = WaitHandle.WaitAny(handles); if (handles[index] == portListenerThreadShutdownEvent) { log.Trace("Shutdown event detected."); break; } TcpClient client = null; NetworkStream stream = null; try { client = acceptTask.Result; stream = client.GetStream(); byte[] buffer = new byte[1024]; int byteCount = stream.Read(buffer, 0, buffer.Length); if (byteCount > 0) { string dataStr = Encoding.UTF8.GetString(buffer, 0, byteCount); log.Trace("Received {0} bytes of data:\n{1}", byteCount, dataStr); log.Trace("Sending the data back to client."); stream.Write(buffer, 0, byteCount); stream.Flush(); Thread.Sleep(100); } else { log.Trace("Connection to client has been terminated."); } } catch (Exception e) { log.Error("Exception occurred: {0}", e.ToString()); } if (stream != null) { stream.Dispose(); } if (client != null) { client.Dispose(); } } log.Trace("Stopping listener."); listener.Stop(); } catch (Exception e) { log.Error("Exception occurred: {0}", e.ToString()); } log.Trace("(-)"); }
/// <summary> /// Waits for a next block to be available (downloaded). /// </summary> /// <param name="cancellationToken">Cancellation token to allow the caller to cancel waiting for the next block.</param> /// <returns>Next block or null if a reorganization happened on the chain.</returns> private LookaheadResult NextBlockCore(CancellationToken cancellationToken) { this.logger.LogTrace("()"); LookaheadResult res = new LookaheadResult(); while (res.Block == null) { cancellationToken.ThrowIfCancellationRequested(); this.logger.LogTrace("Requesting block at height {0}.", this.location.Height + 1); ChainedBlock header = this.Chain.GetBlock(this.location.Height + 1); DownloadedBlock block; bool isDownloading = false; bool isReady = false; if (header != null) { this.CheckBlockStatus(header.HashBlock, out isDownloading, out isReady); } // If block has been downloaded and is ready to be consumed, then remove it from the list of downloaded blocks and consume it. if (isReady && this.TryRemoveDownloadedBlock(header.HashBlock, out block)) { this.logger.LogTrace("Consuming block '{0}'.", header.HashBlock); if (header.Previous.HashBlock != this.location.HashBlock) { this.logger.LogTrace("Blockchain reorganization detected."); break; } this.SetLocation(header); lock (this.bufferLock) { this.currentBufferedSize -= block.Length; this.currentBufferedCount--; } this.consumed.Set(); res.Block = block.Block; } else { // Otherwise we either have reorg, or we reached the best chain tip. if (header == null) { if (!this.Chain.Contains(this.location.HashBlock)) { this.logger.LogTrace("Blockchain reorganization detected."); break; } this.logger.LogTrace("Hash of the next block is not known."); } else { this.logger.LogTrace("Block not available."); // Or the block is still being downloaded or we need to ask for this block to be downloaded. if (!isDownloading) { this.AskBlocks(new ChainedBlock[] { header }); } this.OnStalling(header); } while (!cancellationToken.IsCancellationRequested) { var handles = new WaitHandle[] { this.pushed, this.consumed, cancellationToken.WaitHandle }; int handleIndex = WaitHandle.WaitAny(handles, WaitNextBlockRoundTimeMs); if ((handleIndex != WaitHandle.WaitTimeout) && (handles[handleIndex] == this.consumed)) { // Block has been consumed, check if we can ask for more blocks. this.logger.LogTrace("Block has been previously consumed."); this.ProcessQueue(); } else { // Block has been pushed or wait timed out or cancellation token triggered. // All cases are handled in external loop, so escape the inner loop. break; } } } } this.logger.LogTrace("(-):'{0}'", res); return(res); }
/// <summary> /// Сохранение внесенных изменений /// </summary> /// <returns>Ошибка выполнения</returns> public override Errors SaveChanges() { Errors errRes = Errors.NoError, bErr = Errors.NoError; int indxEv = -1; m_evSaveChangesComplete.Reset(); lock (m_lockResSaveChanges) { m_listResSaveChanges.Clear(); } int prevIndxTECComponent = indxTECComponents; foreach (RDGStruct[] curRDGValues in m_listCurRDGValues) { bErr = Errors.NoError; for (INDEX_WAITHANDLE_REASON i = INDEX_WAITHANDLE_REASON.ERROR; i < (INDEX_WAITHANDLE_REASON.ERROR + 1); i++) { ((ManualResetEvent)m_waitHandleState[(int)i]).Reset(); } if (modeTECComponent(m_listTECComponentIndexDetail[m_listCurRDGValues.IndexOf(curRDGValues)]) == FormChangeMode.MODE_TECCOMPONENT.TG) { indxEv = WaitHandle.WaitAny(m_waitHandleState); if (indxEv == 0) { indxTECComponents = m_listTECComponentIndexDetail[m_listCurRDGValues.IndexOf(curRDGValues)]; curRDGValues.CopyTo(m_curRDGValues, 0); bErr = base.BaseSaveChanges(); } else { break; } } else if (modeTECComponent(m_listTECComponentIndexDetail[m_listCurRDGValues.IndexOf(curRDGValues)]) == FormChangeMode.MODE_TECCOMPONENT.GTP) { indxEv = WaitHandle.WaitAny(m_waitHandleState); if (indxEv == 0) { indxTECComponents = m_listTECComponentIndexDetail[m_listCurRDGValues.IndexOf(curRDGValues)]; curRDGValues.CopyTo(m_curRDGValues, 0); bErr = base.BaseSaveChanges(); } else { break; } } ; lock (m_lockResSaveChanges) { m_listResSaveChanges.Add(bErr); if (!(bErr == Errors.NoError) && (errRes == Errors.NoError)) { errRes = bErr; } else { ; } } } indxTECComponents = prevIndxTECComponent; //if (indxEv == 0) //if (errRes == Errors.NoError) m_evSaveChangesComplete.Set(); //else ; if (!(saveComplete == null)) { saveComplete(); } else { ; } return(errRes); }
void Run(string emulator) { if (emulator == null) { return; } var port = string.IsNullOrEmpty(Port) ? "" : $" -port {Port}"; var arguments = $"{Arguments ?? string.Empty} -verbose -no-boot-anim -no-audio -no-snapshot -cache-size 512 -timezone \"Etc/UTC\" -avd {ImageName}{port}"; Log.LogMessage(MessageImportance.Low, $"Tool {emulator} execution started with arguments: {arguments}"); var psi = new ProcessStartInfo() { FileName = emulator, Arguments = arguments, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WindowStyle = ProcessWindowStyle.Hidden, }; Log.LogMessage(MessageImportance.Low, $"Environment variables being passed to the tool:"); var p = new Process() { StartInfo = psi, }; if (!string.IsNullOrEmpty(AndroidSdkHome)) { psi.EnvironmentVariables ["ANDROID_HOME"] = AndroidSdkHome; Log.LogMessage(MessageImportance.Low, $"\tANDROID_HOME=\"{AndroidSdkHome}\""); } var sawError = new AutoResetEvent(false); DataReceivedEventHandler output = null; output = (o, e) => { Log.LogMessage(MessageImportance.Low, $"[emulator stdout] {e.Data}"); if (string.IsNullOrWhiteSpace(e.Data)) { return; } if (e.Data.StartsWith("Hax ram_size", StringComparison.Ordinal) && e.Data.EndsWith(" 0x0", StringComparison.Ordinal)) { Log.LogError("Emulator failed to start: ram_size is 0MB! Please re-install HAXM."); sawError.Set(); } if (e.Data.IndexOf("ERROR:", StringComparison.Ordinal) >= 0) { Log.LogError($"Emulator failed to start: {e.Data}"); sawError.Set(); } }; DataReceivedEventHandler error = null; error = (o, e) => { Log.LogMessage(MessageImportance.Low, $"[emulator stderr] {e.Data}"); if (string.IsNullOrWhiteSpace(e.Data)) { return; } if (e.Data.StartsWith("Failed to sync", StringComparison.Ordinal) || e.Data.Contains("Internal error")) { Log.LogError($"Emulator failed to start: {e.Data}"); Log.LogError($"Do you have another VM running on the machine? If so, please try exiting the VM and try again."); sawError.Set(); } if (e.Data.StartsWith("Unknown hax vcpu return", StringComparison.Ordinal)) { Log.LogError($"Emulator failed to start: `{e.Data}`. Please try again?"); sawError.Set(); } // The following may not be fatal: // [emulator stderr] eglMakeCurrent failed in binding subwindow! if (e.Data.IndexOf("ERROR:", StringComparison.Ordinal) >= 0 || (e.Data.IndexOf(" failed ", StringComparison.Ordinal) >= 0 && e.Data.IndexOf("eglMakeCurrent", StringComparison.Ordinal) == -1)) { Log.LogError($"Emulator failed to start: {e.Data}"); sawError.Set(); } }; p.OutputDataReceived += output; p.ErrorDataReceived += error; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); const int Timeout = 20 * 1000; int i = WaitHandle.WaitAny(new[] { sawError }, millisecondsTimeout: Timeout); if (i == 0 || Log.HasLoggedErrors) { p.Kill(); return; } p.CancelOutputRead(); p.CancelErrorRead(); p.OutputDataReceived -= output; p.ErrorDataReceived -= error; p.OutputDataReceived += WriteProcessOutputMessage; p.ErrorDataReceived += WriteProcessErrorMessage; p.BeginOutputReadLine(); p.BeginErrorReadLine(); EmulatorProcessId = p.Id; }
/// <summary> /// The core queue processing method /// </summary> /// <param name="state"></param> private void ProcessQueue() { CancellationToken token = this.processQueueCancelToken.Token; WaitHandle[] waitHandles = new WaitHandle[2] { this.itemQueuedEvent, token.WaitHandle }; while (true) { // wait for with an item to be queued or the a cancellation request WaitHandle.WaitAny(waitHandles); if (token.IsCancellationRequested) { break; } try { // dispatch all pending queue items while (this.HasPendingQueueItems) { QueueItem queueItem = GetNextQueueItem(); if (queueItem == null) { continue; } IBindingContext bindingContext = GetOrCreateBindingContext(queueItem.Key); if (bindingContext == null) { queueItem.ItemProcessed.Set(); continue; } bool lockTaken = false; try { // prefer the queue item binding item, otherwise use the context default timeout int bindTimeout = queueItem.BindingTimeout ?? bindingContext.BindingTimeout; // handle the case a previous binding operation is still running if (!bindingContext.BindingLock.WaitOne(queueItem.WaitForLockTimeout ?? 0)) { queueItem.Result = queueItem.TimeoutOperation != null ? queueItem.TimeoutOperation(bindingContext) : null; continue; } bindingContext.BindingLock.Reset(); lockTaken = true; // execute the binding operation object result = null; CancellationTokenSource cancelToken = new CancellationTokenSource(); // run the operation in a separate thread var bindTask = Task.Run(() => { try { result = queueItem.BindOperation( bindingContext, cancelToken.Token); } catch (Exception ex) { Logger.Write(TraceEventType.Error, "Unexpected exception on the binding queue: " + ex.ToString()); if (queueItem.ErrorHandler != null) { result = queueItem.ErrorHandler(ex); } } }); // check if the binding tasks completed within the binding timeout if (bindTask.Wait(bindTimeout)) { queueItem.Result = result; } else { cancelToken.Cancel(); // if the task didn't complete then call the timeout callback if (queueItem.TimeoutOperation != null) { queueItem.Result = queueItem.TimeoutOperation(bindingContext); } lockTaken = false; bindTask .ContinueWith((a) => bindingContext.BindingLock.Set()) .ContinueWithOnFaulted(t => Logger.Write(TraceEventType.Error, "Binding queue threw exception " + t.Exception.ToString())); } } catch (Exception ex) { // catch and log any exceptions raised in the binding calls // set item processed to avoid deadlocks Logger.Write(TraceEventType.Error, "Binding queue threw exception " + ex.ToString()); } finally { if (lockTaken) { bindingContext.BindingLock.Set(); } queueItem.ItemProcessed.Set(); } // if a queue processing cancellation was requested then exit the loop if (token.IsCancellationRequested) { break; } } } finally { lock (this.bindingQueueLock) { // verify the binding queue is still empty if (this.bindingQueue.Count == 0) { // reset the item queued event since we've processed all the pending items this.itemQueuedEvent.Reset(); } } } } }
internal static int WaitAny(WaitHandle[] waitHandles) { return(WaitHandle.WaitAny(waitHandles)); }
private void PortScannerManager(string host) { var ports = new List <int>(); foreach (string s in txtPorts.Text.Split(',')) { int p; if (int.TryParse(s, out p)) { if (p < 65535 && p > 0) { ports.Add(p); } } } UISync.Execute(() => pbScanner.Value = 0); var manualEvents = new ManualResetEvent[MaxThreads]; int j; for (int k = 0; k < MaxThreads; k++) { manualEvents[k] = new ManualResetEvent(true); } var ipranges = new List <string>(); if (host == LocRm.GetString("AllAdaptors")) { ipranges.AddRange(from string s in ddlHost.Items where s != LocRm.GetString("AllAdaptors") select s); } else { ipranges.Add(host); } UISync.Execute(() => pbScanner.Maximum = ipranges.Count * 254); Logger.LogMessage("Scanning LAN"); j = 0; foreach (string IP in DnsEntries) { string ip = IP; int k = j; var scanner = new Thread(p => PortScanner(ports, ip, manualEvents[k])); scanner.Start(); j = WaitHandle.WaitAny(manualEvents); UISync.Execute(() => pbScanner.PerformStep()); if (_exiting) { break; } } if (!_exiting) { j = 0; foreach (string shost in ipranges) { for (int i = 0; i < 255; i++) { string ip = shost.Replace("x", i.ToString(CultureInfo.InvariantCulture)); if (!DnsEntries.Contains(ip)) { int k = j; manualEvents[k].Reset(); var scanner = new Thread(p => PortScanner(ports, ip, manualEvents[k])); scanner.Start(); j = WaitHandle.WaitAny(manualEvents); UISync.Execute(() => pbScanner.PerformStep()); } if (_exiting) { break; } } if (_exiting) { break; } } } if (j > 0) { WaitHandle.WaitAll(manualEvents); } //populate MAC addresses try { var arpStream = ExecuteCommandLine("arp", "-a"); // Consume first three lines for (int i = 0; i < 3; i++) { arpStream.ReadLine(); } // Read entries while (!arpStream.EndOfStream) { var line = arpStream.ReadLine(); if (line != null) { line = line.Trim(); while (line.Contains(" ")) { line = line.Replace(" ", " "); } var parts = line.Trim().Split(' '); if (parts.Length == 3) { for (int i = 0; i < _dt.Rows.Count; i++) { DataRow dr = _dt.Rows[i]; string ip = parts[0]; if (ip == dr["IP Address"].ToString().Split(':')[0]) { dr["MAC Address"] = parts[1]; } } } } } _dt.AcceptChanges(); } catch (Exception ex) { Logger.LogException(ex); } UISync.Execute(ResetControls); }
/// <summary> /// Worker thread to perform the file operations /// </summary> private void ThreadRunImpl() { // Initialize xstore blobcontainer and connection in the thread // This is to prevent we block the dispatcher // Connect to azure blob storage string connectionString = this.storeParams.ConnectionString; var storageAccount = CloudStorageAccount.Parse(connectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); blobClient.DefaultRequestOptions = new BlobRequestOptions(); blobClient.DefaultRequestOptions.MaximumExecutionTime = new TimeSpan(0, 5, 0); // For large file copies set up a custom timeout period; and using parallel settings blobClient.DefaultRequestOptions.ParallelOperationThreadCount = XStoreCommon.ParallelOperationThreadCount; // Get and create the container CloudBlobContainer blobContainer = blobClient.GetContainerReference(this.storeParams.Container); while (WaitHandle.WaitAny(this.syncEvents.EventArray) != 1) { XStoreFileOperationTask task = this.xstoreTaskPool.GetTaskFromTaskQueue(); if (null != task) { // We have got valid task if (task.RetryCount > 0) { // Sleep random time to prevent all worker threads do the next try at the same time Random rand = new Random(DateTime.Now.Millisecond + this.workerID); int timeoutInSeconds = rand.Next(MinRetryInSeconds, MaxRetryInSeconds); traceSource.WriteError( ClassName, string.Format(CultureInfo.InvariantCulture, "[RETRY] sleep {0} seconds to work on {1}", timeoutInSeconds, task.SrcUri)); Thread.Sleep(timeoutInSeconds * 1000); } if (task.IsFolder && task.OpType != XStoreFileOperationTask.XStoreTaskType.EndCopyFromXStoreToSMB && task.OpType != XStoreFileOperationTask.XStoreTaskType.EndCopyFromSMBToXStore && task.OpType != XStoreFileOperationTask.XStoreTaskType.EndCopyFromXStoreToXStore) { try { this.HandleFolder(blobContainer, task); } catch (Exception e) { traceSource.WriteError( ClassName, string.Format(CultureInfo.InvariantCulture, "[{0}] [{1}] EXCEPTION = {2}", Thread.CurrentThread.ManagedThreadId, DateTime.Now, e.Message)); if (e is TimeoutException) { throw; } if (e is StorageException && e.InnerException is TimeoutException) { throw new TimeoutException(e.InnerException.Message); } if (ExceptionHandler.IsFatalException(e)) { throw; } this.RetryTask(task); } finally { this.xstoreTaskPool.DecrementTaskCount(); } } else { try { switch (task.OpType) { case XStoreFileOperationTask.XStoreTaskType.CopyFromXStoreToSMB: this.TransferFileFromXStoreToSMB(blobContainer, task); break; case XStoreFileOperationTask.XStoreTaskType.CopyFromSMBToXStore: this.TransferFileFromSMBToXStore(blobContainer, task); break; case XStoreFileOperationTask.XStoreTaskType.CopyFromXStoreToXStore: this.TransferFileFromXStoreToXStore(blobContainer, task); break; case XStoreFileOperationTask.XStoreTaskType.RemoveFromXStore: DeleteFileFromXStore(blobContainer, task); break; case XStoreFileOperationTask.XStoreTaskType.EndCopyFromSMBToXStore: EndCopyFromSMBToXStore(blobContainer, task); break; case XStoreFileOperationTask.XStoreTaskType.EndCopyFromXStoreToSMB: EndCopyFromXStoreToSMB(task); break; case XStoreFileOperationTask.XStoreTaskType.EndCopyFromXStoreToXStore: EndCopyFromXStoreToXStore(blobContainer, task); break; default: break; } } catch (Exception e) { traceSource.WriteError( ClassName, string.Format(CultureInfo.InvariantCulture, "[{0}] [{1}] EXCEPTION = {2}", Thread.CurrentThread.ManagedThreadId, DateTime.Now, e.Message)); string extraTracing = task.GetExtraTracing(); if (!string.IsNullOrEmpty(extraTracing)) { traceSource.WriteInfo(ClassName, extraTracing); } if (e is TimeoutException) { throw; } if (e is StorageException && e.InnerException is TimeoutException) { throw new TimeoutException(e.InnerException.Message); } if (ExceptionHandler.IsFatalException(e)) { throw; } this.RetryTask(task); } finally { this.xstoreTaskPool.DecrementTaskCount(); } } } } }
private void SocketLoop() { var readBuffer = new byte[BufferSize]; Tuple <byte[], int, int> outgoing = null; IAsyncResult arr = null, arw = null; var handles = new WaitHandle[] { null, null, _endHandle }; try { while (_tcpClient.Connected) { if (arr == null) { arr = _stream.BeginRead(readBuffer, 0, BufferSize, null, null); } _writeHandle.Reset(); if (arw == null && _writeQueue.TryDequeue(out outgoing)) { if (outgoing.Item1 == null) { break; } arw = _stream.BeginWrite(outgoing.Item1, outgoing.Item2, outgoing.Item3, null, null); } handles[0] = arr.AsyncWaitHandle; handles[1] = arw != null ? arw.AsyncWaitHandle : _writeHandle; switch (WaitHandle.WaitAny(handles)) { case 0: int count = _stream.EndRead(arr); arr = null; if (count <= 0) { return; } this.OnReceived(readBuffer, count); break; case 1: if (arw != null) { _stream.EndWrite(arw); arw = null; this.OnSent(outgoing.Item1, outgoing.Item2, outgoing.Item3); } break; case 2: if (arw != null) { _stream.EndWrite(arw); } return; } } } catch (Exception ex) { this.OnError(ex); } finally { _tcpClient.Close(); this.OnDisconnected(); } return; }
protected override void Run() { Thread.Sleep(5 * 1000); lock (_guideProgramsToImportLock) { _newProgramsToImportEvent = new AutoResetEvent(false); } try { int interval = 1 * 60 * 1000; #if DEBUG interval = 5000; #endif bool aborted = false; while (!aborted) { try { List <GuideProgram> guidePrograms = GetProgramsToImport(); while (guidePrograms != null) { using (GuideServiceAgent tvGuideAgent = new GuideServiceAgent()) { Log.Debug("ArgusTV.Recorder.MediaPortalTvServer: ArgusTVDvbEpg: importing {0} programs into ARGUS TV", guidePrograms.Count); foreach (GuideProgram guideProgram in guidePrograms) { tvGuideAgent.ImportProgram(guideProgram, GuideSource.DvbEpg); aborted = this.StopThreadEvent.WaitOne(0, false); if (aborted) { break; } } } aborted = this.StopThreadEvent.WaitOne(0); if (aborted) { break; } guidePrograms = GetProgramsToImport(); } if (!aborted) { aborted = (0 == WaitHandle.WaitAny(new WaitHandle[] { this.StopThreadEvent, _newProgramsToImportEvent }, interval, false)); } } catch (Exception ex) { Log.Error("ArgusTVDvbEpg error: {0}", ex.Message); // Delay for a short while and then restart. aborted = this.StopThreadEvent.WaitOne(30 * 1000, false); } } } finally { lock (_guideProgramsToImportLock) { _newProgramsToImportEvent.Close(); _newProgramsToImportEvent = null; } } }
/// <summary> /// Open a DCC session that listens on the specified port. Once a connection is established, there is no difference /// between this session and one that started with an outgoing connection. /// </summary> /// <param name="startPort">The lowest available port to listen on.</param> /// <param name="startPort">The highest available port to listen on.</param> /// <returns>Returns the actual port number the session is listening on.</returns> public int Listen(int lowPort, int highPort) { if (lowPort > ushort.MaxValue || lowPort < MinPort) { throw new ArgumentException("Invalid port.", "lowPort"); } if (highPort > ushort.MaxValue || highPort < lowPort) { throw new ArgumentException("Invalid port.", "highPort"); } while (true) { _listener = new TcpListener(IPAddress.Any, lowPort); try { _listener.Start(); break; } catch (SocketException) { if (++lowPort > ushort.MaxValue) { throw new InvalidOperationException("No available ports."); } } } _socketThread = new Thread(new ThreadStart(() => { var ar = _listener.BeginAcceptTcpClient(null, null); int index = WaitHandle.WaitAny(new[] { ar.AsyncWaitHandle, _endHandle }, ListenTimeout); switch (index) { case 0: try { _tcpClient = _listener.EndAcceptTcpClient((IAsyncResult)ar); } catch (SocketException) { break; } finally { _listener.Stop(); } var endpoint = (IPEndPoint)_tcpClient.Client.RemoteEndPoint; this.Address = endpoint.Address; this.Port = endpoint.Port; this.OnConnected(); try { this.SocketLoop(); } catch (Exception ex) { this.OnError(ex); } break; case 1: _listener.Stop(); break; case WaitHandle.WaitTimeout: _listener.Stop(); this.OnError(new TimeoutException()); break; } })); _socketThread.IsBackground = true; _socketThread.Start(); return(lowPort); }
private void DelayProc() { var wh = new WaitHandle[] { _evExit, _evGotDelayedNotification }; var notifications = new List <IRepositoryChangedNotification>(); while (true) { lock (_delayedNotifications) { while (_delayedNotifications.Count != 0) { notifications.Add(_delayedNotifications.Dequeue()); } } if (notifications.Count == 0) { if (WaitHandle.WaitAny(wh) == 0) { return; } continue; } switch (WaitHandle.WaitAny(wh, _notificationDelayTime)) { case 0: return; case 1: continue; case WaitHandle.WaitTimeout: WorktreeUpdatedNotification globalwtn = null; int count = 0; foreach (var n in notifications) { var wtn = n as WorktreeUpdatedNotification; if (wtn != null) { if (count == 0) { globalwtn = wtn; ++count; } else { globalwtn = new WorktreeUpdatedNotification(""); ++count; } } else { EmitNotification(n); } } notifications.Clear(); if (globalwtn != null) { EmitNotification(globalwtn); } break; } } }
internal IFetchedJob Dequeue_Transaction(string[] queues, CancellationToken cancellationToken) { if (queues == null) { throw new ArgumentNullException(nameof(queues)); } if (queues.Length == 0) { throw new ArgumentException("Queue array must be non-empty.", nameof(queues)); } long timeoutSeconds = (long)_options.InvisibilityTimeout.Negate().TotalSeconds; FetchedJob fetchedJob; string fetchJobSqlTemplate = @" UPDATE """ + _options.SchemaName + @""".""jobqueue"" SET ""fetchedat"" = NOW() AT TIME ZONE 'UTC' WHERE ""id"" = ( SELECT ""id"" FROM """ + _options.SchemaName + $@""".""jobqueue"" WHERE ""queue"" = ANY (@queues) AND ""fetchedat"" {{0}} ORDER BY ""queue"", ""fetchedat"", ""jobid"" FOR UPDATE SKIP LOCKED LIMIT 1 ) RETURNING ""id"" AS ""Id"", ""jobid"" AS ""JobId"", ""queue"" AS ""Queue"", ""fetchedat"" AS ""FetchedAt""; "; var fetchConditions = new[] { "IS NULL", $"< NOW() AT TIME ZONE 'UTC' + INTERVAL '{timeoutSeconds.ToString(CultureInfo.InvariantCulture)} SECONDS'" }; var currentQueryIndex = 0; do { cancellationToken.ThrowIfCancellationRequested(); string fetchJobSql = string.Format(fetchJobSqlTemplate, fetchConditions[currentQueryIndex]); Utils.Utils.TryExecute(() => { var connection = _storage.CreateAndOpenConnection(); try { using (var trx = connection.BeginTransaction(IsolationLevel.ReadCommitted)) { var jobToFetch = connection.Query <FetchedJob>( fetchJobSql, new { queues = queues.ToList() }, trx) .SingleOrDefault(); trx.Commit(); return(jobToFetch); } } finally { _storage.ReleaseConnection(connection); } }, out fetchedJob, ex => { NpgsqlException npgSqlException = ex as NpgsqlException; PostgresException postgresException = ex as PostgresException; bool smoothException = false; if (postgresException != null) { if (postgresException.SqlState.Equals("40001")) { smoothException = true; } } return(smoothException); }); if (fetchedJob == null) { if (currentQueryIndex == fetchConditions.Length - 1) { WaitHandle.WaitAny(new [] { cancellationToken.WaitHandle, NewItemInQueueEvent }, _options.QueuePollInterval); cancellationToken.ThrowIfCancellationRequested(); } } currentQueryIndex = (currentQueryIndex + 1) % fetchConditions.Length; } while (fetchedJob == null); return(new PostgreSqlFetchedJob( _storage, _options, fetchedJob.Id, fetchedJob.JobId.ToString(CultureInfo.InvariantCulture), fetchedJob.Queue)); }
private void PlayThread() { ResamplerDmoStream resamplerDmoStream = null; IWaveProvider playbackProvider = sourceProvider; Exception exception = null; try { if (dmoResamplerNeeded) { resamplerDmoStream = new ResamplerDmoStream(sourceProvider, outputFormat); playbackProvider = resamplerDmoStream; } // fill a whole buffer bufferFrameCount = audioClient.BufferSize; bytesPerFrame = outputFormat.Channels * outputFormat.BitsPerSample / 8; readBuffer = new byte[bufferFrameCount * bytesPerFrame]; FillBuffer(playbackProvider, bufferFrameCount); // Create WaitHandle for sync var waitHandles = new WaitHandle[] { frameEventWaitHandle }; audioClient.Start(); while (playbackState != PlaybackState.Stopped) { // If using Event Sync, Wait for notification from AudioClient or Sleep half latency int indexHandle = 0; if (isUsingEventSync) { indexHandle = WaitHandle.WaitAny(waitHandles, 3 * latencyMilliseconds, false); } else { Thread.Sleep(latencyMilliseconds / 2); } // If still playing and notification is ok if (playbackState == PlaybackState.Playing && indexHandle != WaitHandle.WaitTimeout) { // See how much buffer space is available. int numFramesPadding; if (isUsingEventSync) { // In exclusive mode, always ask the max = bufferFrameCount = audioClient.BufferSize numFramesPadding = (shareMode == AudioClientShareMode.Shared) ? audioClient.CurrentPadding : 0; } else { numFramesPadding = audioClient.CurrentPadding; } int numFramesAvailable = bufferFrameCount - numFramesPadding; if (numFramesAvailable > 10) // see https://naudio.codeplex.com/workitem/16363 { FillBuffer(playbackProvider, numFramesAvailable); } } } Thread.Sleep(latencyMilliseconds / 2); audioClient.Stop(); if (playbackState == PlaybackState.Stopped) { audioClient.Reset(); } } catch (Exception e) { exception = e; } finally { if (resamplerDmoStream != null) { resamplerDmoStream.Dispose(); } RaisePlaybackStopped(exception); } }
/// <summary> /// 实时获取当前揽件重量 /// </summary> private void GetWight() { // 串口触发事件和线程退出事件 WaitHandle[] handles = new WaitHandle[] { _WightWaitHandle, _ExitHandle }; while (_bLooping) { int bWait = WaitHandle.WaitAny(handles); // 退出线程 if (bWait == 1) { break; } // 实时称重数据回调 if (Interlocked.Read(ref _RealWightFlag) == 1) { if (ScaleWight != null) { double tmp = Interlocked.CompareExchange(ref _RealWight, 0, 0); WeightEventArgs e = new WeightEventArgs(tmp); e.RealWeight = false; ScaleWight(this, e); } } if (Interlocked.Read(ref _SampleWeightFlag) == 1) { StringBuilder _weightList = new StringBuilder(); for (int i = 0; i < _nSampleCountPerGroup; i++) { _weightList.Append(" "); _weightList.Append(_SampleArray[i].ToString()); } string weightss = _weightList.ToString(); // 计算样本平均值 Double avg = _SampleArray.Average(); // 排除最小电子称精度误差一下的重量 if (avg < 0.02 || Array.IndexOf(_SampleArray, 0.0) != -1) { // 重新取样运算 lock (_LockFlagObj) { Interlocked.CompareExchange(ref _SampleWeightFlag, 0, 1); Array.Clear(_SampleArray, 0, _SampleArray.Length); } MvBarCode.MvBarCodeGlobalVar.Log.DebugFormat("实时重量:数值太小 return:{0}", weightss); continue; } // 计算样本方差大小 Double sum = 0.0; foreach (var x in _SampleArray) { sum += (x - avg) * (x - avg); } // 计算当前样本集合的方差值 Double variance = sum / _nSampleCountPerGroup; // 校验样本的方差值和最大误差之间的大小关系 if (avg >= 0.03 /*kg*/ && variance <= _MaxDeviation) { lock (_LockFlagObj) { Interlocked.CompareExchange(ref _SampleFlag, 0, 1); Interlocked.CompareExchange(ref _RealWightFlag, 0, 1); Interlocked.CompareExchange(ref _SampleWeightFlag, 0, 1); Array.Clear(_SampleArray, 0, _SampleArray.Length); } // 最终数据回调 if (ScaleWight != null) { WeightEventArgs e = new WeightEventArgs(avg); e.RealWeight = true; ScaleWight(this, e); } } // 获取采样样本 else { lock (_LockFlagObj) { MvBarCode.MvBarCodeGlobalVar.Log.DebugFormat("实时重量:不符合精度要求数据:{0}", weightss); Array.Clear(_SampleArray, 0, _SampleArray.Length); Interlocked.CompareExchange(ref _SampleWeightFlag, 0, 1); } } } Thread.Sleep(1); } }
// 线程connect()到主机 public int NewConnectSocket(string strHostName, int nPort, out string strError) { strError = ""; this.m_strHostName = strHostName; this.m_nPort = nPort; // 在线程之前试探Close(); this.CloseSocket(); this.eventClose.Reset(); this.eventFinished.Reset(); this.strErrorString = ""; this.nErrorCode = 0; Thread clientThread = new Thread(new ThreadStart(ConnectThread)); clientThread.Start(); // 等待线程结束 WaitHandle[] events = new WaitHandle[2]; events[0] = this.eventClose; events[1] = this.eventFinished; int nIdleTimeCount = 0; int nIdleTicks = 100; REDO: DoIdle(); int index = 0; try { index = WaitHandle.WaitAny(events, nIdleTicks, false); } catch (System.Threading.ThreadAbortException ex) { strError = "线程被杀死"; return(-1); } if (index == WaitHandle.WaitTimeout) { nIdleTimeCount += nIdleTicks; if (nIdleTicks >= this.Timeout) { // 超时 strError = "超时 (" + this.Timeout + "毫秒)"; return(-1); } goto REDO; } else if (index == 0) { // 得到Close信号 strError = "通道被切断"; return(-1); } else { // 得到finish信号 if (nErrorCode != 0) { strError = this.strErrorString; return(nErrorCode); } return(0); } return(-1); }
/// <summary> /// Отобразить значения в представлении /// </summary> /// <param name="date">Дата, за которую получены значения для отображения</param> /// <param name="bResult">Признак наличия новых значений, иначе требуется изменить оформление представления</param> public override void SetDataGridViewAdmin(DateTime date, bool bResult) { int offset = -1; FormChangeMode.KeyDevice nextKey; string strFmtDatetime = string.Empty; IAsyncResult iar; Action <bool> exportPBRValuesEnded = delegate(bool error) { ModeGetRDGValues = AdminTS.MODE_GET_RDG_VALUES.DISPLAY; btnRefresh.PerformClick(); if (error == true) { MessageBox.Show(this, $"Произошла ошибка.{Environment.NewLine}Попробуйте выполнить операцию позднее.", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { ; } }; if ((ModeGetRDGValues & AdminTS.MODE_GET_RDG_VALUES.DISPLAY) == AdminTS.MODE_GET_RDG_VALUES.DISPLAY) { if (bResult == true) { //??? не очень изящное решение if (IsHandleCreated == true) { if (InvokeRequired == true) { //m_evtAdminTableRowCount.Reset (); // кол-во строк может быть изменено(нормализовано) только в том потоке,в котором было выполнено создание элемента управления iar = this.BeginInvoke(new DelegateBoolFunc(normalizedTableHourRows), InvokeRequired); //??? ожидать, пока не завершится выполнение предыдущего потока //m_evtAdminTableRowCount.WaitOne (System.Threading.Timeout.Infinite); WaitHandle.WaitAny(new WaitHandle [] { iar.AsyncWaitHandle }, System.Threading.Timeout.Infinite); this.EndInvoke(iar); } else { normalizedTableHourRows(InvokeRequired); } } else { normalizedTableHourRows(false); if (!((ModeGetRDGValues & AdminTS.MODE_GET_RDG_VALUES.UNIT_TEST) == AdminTS.MODE_GET_RDG_VALUES.UNIT_TEST)) { Logging.Logg().Error(@"PanelAdminKomDisp::setDataGridViewAdmin () - ... BeginInvoke (normalizedTableHourRows) - ...", Logging.INDEX_MESSAGE.D_001); } else { ; } } ((DataGridViewAdminKomDisp)this.dgwAdminTable).m_PBR_0 = m_admin.m_curRDGValues_PBR_0; //??? отобразить значения - почему не внутри класса-объекта представления for (int i = 0; i < m_admin.m_curRDGValues.Length; i++) { strFmtDatetime = m_admin.GetFmtDatetime(i); offset = m_admin.GetSeasonHourOffset(i + 1); this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.DATE_HOUR].Value = date.AddHours(i + 1 - offset).ToString(strFmtDatetime); //this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.DATE_HOUR].Style.BackColor = this.dgwAdminTable.BackColor; this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.PLAN].Value = m_admin.m_curRDGValues [i].pbr.ToString("F2"); this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.PLAN].ToolTipText = m_admin.m_curRDGValues [i].pbr_number; //this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.PLAN].Style.BackColor = this.dgwAdminTable.BackColor; if (i > 0) { this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.UDGe].Value = (((m_admin.m_curRDGValues [i].pbr + m_admin.m_curRDGValues [i - 1].pbr) / 2) + m_admin.m_curRDGValues [i].recomendation).ToString("F2"); } else { this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.UDGe].Value = (((m_admin.m_curRDGValues [i].pbr + m_admin.m_curRDGValues_PBR_0) / 2) + m_admin.m_curRDGValues [i].recomendation).ToString("F2"); } //this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.UDGe].Style.BackColor = this.dgwAdminTable.BackColor; this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.RECOMENDATION].Value = m_admin.m_curRDGValues [i].recomendation.ToString("F2"); this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.RECOMENDATION].ToolTipText = m_admin.m_curRDGValues [i].dtRecUpdate.ToString(); //this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.RECOMENDATION].Style.BackColor = this.dgwAdminTable.BackColor; this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.FOREIGN_CMD].Value = m_admin.m_curRDGValues [i].fc.ToString(); //this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.FOREIGN_CMD].Style.BackColor = this.dgwAdminTable.BackColor; this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.DEVIATION_TYPE].Value = m_admin.m_curRDGValues [i].deviationPercent.ToString(); //this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.DEVIATION_TYPE].Style.BackColor = this.dgwAdminTable.BackColor; this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.DEVIATION].Value = m_admin.m_curRDGValues [i].deviation.ToString("F2"); //this.dgwAdminTable.Rows [i].Cells [(int)DataGridViewAdminKomDisp.COLUMN_INDEX.DEVIATION].Style.BackColor = this.dgwAdminTable.BackColor; } m_admin.CopyCurToPrevRDGValues(); } else { ; } } else if ((ModeGetRDGValues & AdminTS.MODE_GET_RDG_VALUES.EXPORT) == AdminTS.MODE_GET_RDG_VALUES.EXPORT) { nextKey = bResult == true ? Admin.AddValueToExportRDGValues(m_admin.m_curRDGValues, date) : FormChangeMode.KeyDevice.Empty; if (!(nextKey.Id > 0)) { if (InvokeRequired == true) { Invoke((MethodInvoker) delegate() { exportPBRValuesEnded(nextKey.Id < 0); }); } else { exportPBRValuesEnded(nextKey.Id < 0); } } else { Admin.GetRDGValues(nextKey, date); } } // сообщить в модульный тест о завершении очередной итерации EventUnitTestSetDataGridViewAdminCompleted?.Invoke(); }