public void Play(Actions.Action action, object data, bool skipSelf, bool startPauses) { if (IsRunning) { throw new WrongStateException(); } _skipSelfExecute = skipSelf; CurrentAction = action; State = startPauses ? ContextState.Pause : ContextState.Paly; if (startPauses) { _continueEvent.Reset(); } else { _continueEvent.Set(); } if (_executeTask != null) { _executeTask.Dispose(); } _breakEvent.Reset(); lock (this) { _executeTask = new Task(Execute, data); _executeTask.Start(); } }
private static void CloneStringCrossThead_Thread() { try { while (true) { if (_CloneStringCrossThead_Event_Inner.WaitOne(1000) == false) { // 等了1秒没任务了,退出线程。 break; } if (_CloneStringCrossThead_CurrentValue != null) { _CloneStringCrossThead_CurrentValue = new string(_CloneStringCrossThead_CurrentValue.ToCharArray()); } _CloneStringCrossThead_Event.Set(); _CloneStringCrossThead_Event_Inner.Reset(); } } finally { _CloneStringCrossThead_Thread = null; _CloneStringCrossThead_Event.Reset(); _CloneStringCrossThead_Event_Inner.Reset(); } }
public void WaitRender() { ScopeWaitRender.Begin(); mRenderEnd.WaitOne(); mRenderEnd.Reset(); ScopeWaitRender.End(); }
public override void Tick() { mLogicBegin.WaitOne(); mLogicBegin.Reset(); IsTicking = true; TickAwaitEvent(); CEngine.Instance.TryTickLogic(); IsTicking = false; mLogicEnd.Set(); }
public override string Execute(string[] args, LLUUID fromAgentID) { if (args.Length < 1) { return("Usage: searchevents [search text]"); } string searchText = string.Empty; for (int i = 0; i < args.Length; i++) { searchText += args[i] + " "; } searchText = searchText.TrimEnd(); waitQuery.Reset(); Client.Directory.OnEventsReply += new DirectoryManager.EventReplyCallback(Directory_OnEventsReply); Client.Directory.StartEventsSearch(searchText, true, "u", 0, DirectoryManager.EventCategories.All, LLUUID.Random()); string result; if (waitQuery.WaitOne(20000, false) && Client.Network.Connected) { result = "Your query '" + searchText + "' matched " + resultCount + " Events. "; } else { result = "Timeout waiting for simulator to respond."; } Client.Directory.OnEventsReply -= new DirectoryManager.EventReplyCallback(Directory_OnEventsReply); return(result); }
public String PostRequest(Iso8583Request req) { byte[] reqMsg = null; if (req.RequestString != null) { String sReq = req.RequestString.Trim(); if (String.IsNullOrEmpty(sReq)) { throw new HttpResponseException(HttpStatusCode.NoContent); } System.Text.RegularExpressions.Regex ws = new System.Text.RegularExpressions.Regex(@"\s+"); sReq = ws.Replace(sReq, ""); reqMsg = MessageUtility.StringToHex(sReq, true); if (reqMsg == null) { //throw new HttpResponseException(HttpStatusCode.InternalServerError); _outputData = "Error: Invalid request message string (not valid hexadecimal)"; } } try { MessageClient client = new MessageClient(req.ServerHost, req.ServerPort, null, this.PrintModel); client.IsSslEnabled = req.IsSSL; if (req.RequestString != null) { if (reqMsg != null) { client.SendBytes(reqMsg); } } else { client.Model = HttpContext.Current.Session != null ? HttpContext.Current.Session["model"] : null; if (client.Model != null) { _iso8583ResponseEvent.Reset(); client.SendModel(); _iso8583ResponseEvent.WaitOne(); } else { _outputData = "Error: Invalid request message (cannot be null value)"; } } } catch { //throw new HttpResponseException(HttpStatusCode.InternalServerError); _outputData = "Error: Cannot send request message to ISO 8583 server."; } if (_outputData.IndexOf("Error: ") == 0) { Logger.GetInstance().WriteLine(_outputData); } return(_outputData); }
/// <summary> /// 向读卡器请求命令,并取得返回包 /// </summary> /// <param name="cmd">请求的命令</param> /// <param name="data">请求中包含的数据</param> /// <returns></returns> public YCTPacket Request(YCTCommandType cmd, byte[] data) { lock (_PortLocker) { byte[] request = CreateRequest(cmd, data); if (Log) { Ralid.GeneralLibrary.LOG.FileLog.Log("羊城通读卡器", "发送数据: " + HexStringConverter.HexToString(request, " ")); } _Port.OnDataArrivedEvent -= _Port_OnDataArrivedEvent; _buffer.Clear(); _Responsed.Reset(); _Response = null; _Port.OnDataArrivedEvent += _Port_OnDataArrivedEvent; _Port.SendData(request); if (_Responsed.WaitOne(5000)) { if (_Response != null && _Response.CheckCRC() && _Response.Command == (byte)cmd) { _LastError = _Response.Status; return(_Response); } } } _LastError = -1; return(null); }
/// <summary> /// Starts the main loop. /// </summary> public void Run() { // Start the main loop and continue until it's stopped m_running = true; while (m_running) { // Wait on Invoke or Stop methods to be called m_syncEvent.WaitOne(); while (m_methodQueue.Count != 0) { MethodDelegate method = (MethodDelegate)m_methodQueue.Dequeue(); try { // Perform the action method(); } catch (Exception e) { String msg = e.Message + " " + e.InnerException + " " + e.StackTrace; // Send event Safir.Logging.SendSystemLog(Safir.Logging.Severity.Critical, "Unhandled Exception in MainLoop: " + msg); // Terminate the application //Instances.SelfInstance.MainModule.FatalError(); } } m_syncEvent.Reset(); } }
public override string Execute(string[] args, UUID fromAgentID) { if (args.Length < 1) { return("Usage: key2name UUID"); } UUID key; if (!UUID.TryParse(args[0].Trim(), out key)) { return("UUID " + args[0].Trim() + " appears to be invalid"); } result.Remove(0, result.Length); waitQuery.Reset(); Client.Avatars.UUIDNameReply += Avatars_OnAvatarNames; Client.Groups.GroupProfile += Groups_OnGroupProfile; Client.Avatars.RequestAvatarName(key); Client.Groups.RequestGroupProfile(key); if (!waitQuery.WaitOne(10000, false)) { result.AppendLine("Timeout waiting for reply, this could mean the Key is not an avatar or a group"); } Client.Avatars.UUIDNameReply -= Avatars_OnAvatarNames; Client.Groups.GroupProfile -= Groups_OnGroupProfile; return(result.ToString()); }
/// <summary> /// Wraps the Execute call abstracting the child class from the thread synchronization issues. /// </summary> /// <param name="sender">The thimer object that is calling the event listener.</param> /// <param name="e">The arguments passed by the timer to the method.</param> private void OnTimerElapsed(object sender, ElapsedEventArgs e) { //Force other threads to wait until it's finished when calling join. syncMutex.Reset(); //Avoid re-calling the method while it is still operating. timer.Stop(); if (this.IsRunning) { runWatch.Restart(); this.Run(); long runTime = runWatch.ElapsedMilliseconds; this.TotalLagTime += (runTime > this.Interval) ? (runTime - this.Interval) : 0; this.TotalRunTime += runTime; this.RunCount++; runWatch.Stop(); //Re-Start the timer to execute the worker function endlessly. timer.Start(); } //Release threads that might be frozen in join operation. syncMutex.Set(); }
private void Wait() { obj.Reset(); while (obj.WaitOne(10, false) == false) { Application.DoEvents(); } }
/// <summary> /// 跨线程的复制字符串值,用于改变创建字符串的调用堆栈 /// </summary> /// <param name="txt">字符串值</param> /// <returns>复制品</returns> public static string CloneStringCrossThead(string txt) { if (txt == null || txt.Length == 0) { return(txt); } lock (_CloneStringCrossThead_Event) { _CloneStringCrossThead_CurrentValue = txt; _CloneStringCrossThead_Event_Inner.Set(); _CloneStringCrossThead_Event.Reset(); if (_CloneStringCrossThead_Thread == null) { _CloneStringCrossThead_Thread = new System.Threading.Thread(CloneStringCrossThead_Thread); _CloneStringCrossThead_Thread.Start(); } _CloneStringCrossThead_Event.WaitOne(100); return(_CloneStringCrossThead_CurrentValue); } }
/// <summary> /// If the thread <see cref="IsAlive"/>, this method will stop the thread, aborting it if necessary. Waiting the <paramref name="terminationWaitTime"/> time for the <see cref="OnExecute"/> method to terminate on its own before aborting it. /// </summary> /// <param name="terminationWaitTime">The amount of time to wait for the <see cref="OnExecute"/> method to terminate on its own before aborting it.</param> public void Stop(TimeSpan terminationWaitTime) { if (_Thread != null) { try { lock (_SyncLock) { _ExecuteNow = false; _WaitHandle_ThreadStateChange.Reset(); _CancelToken.CancelThread = true; _WaitHandle_StopThread.Set(); } if (!_WaitHandle_ThreadStateChange.WaitOne(terminationWaitTime)) { // timed out (thread still running) _Thread.Abort(); _Thread.Join(terminationWaitTime); } } finally { lock (_SyncLock) { StoppedDate = DateTime.Now; _Thread = null; // close and dispose of all wait handles // fail-safe if (_WaitHandle_StopThread != null) { _WaitHandle_StopThread.Close(); _WaitHandle_StopThread = null; } // the only place where this WaitHandle is being disposed _WaitHandle_ThreadStateChange.Close(); _WaitHandle_ThreadStateChange = null; // fail-safe if (_WaitHandle_ThreadWorkerWorking != null) { _WaitHandle_ThreadWorkerWorking.Close(); _WaitHandle_ThreadWorkerWorking = null; } } // call OnStop() OnStop(); } } }
private void _StartDispatchTask() { if (_dispatchThread != null) { return; } _getDispatchARE = new System.Threading.AutoResetEvent(false); _dispatchThread = new System.Threading.Thread(() => { List <int> lastExecDis = new List <int>(); int keepcount = 100; while (true) { var freestate = serviceItems.ToList().Where(x => x.JobType == 1).Select(x => new int[] { x.TaskId, x.GetFreeCount() }).ToList(); if (freestate.Count > 0 && freestate.Count(x => x[1] > 0) > 0) { try { var pingresult = Ruanal.Core.ApiSdk.SystemApi.GetDispatchWork(freestate); if (pingresult.code > 0) { _getDispatchARE.Reset(); foreach (var a in pingresult.data) { if (lastExecDis.Contains(a.DispatchId)) { continue; } OnDispatchJob(a); lastExecDis.Add(a.DispatchId); while (lastExecDis.Count > keepcount) { lastExecDis.RemoveAt(0); } } } } catch (Exception ex) { RLib.WatchLog.Loger.Error("GetDispatchWork", ex); } } _getDispatchARE.WaitOne(TimeSpan.FromSeconds(_PingSeconds)); } }); _dispatchThread.IsBackground = true; _dispatchThread.Start(); }
/// <summary> /// If the <see cref="OnExecute"/> method is not already running, this will cause the <see cref="OnExecute"/> method to be started immediately. If the <see cref="OnExecute"/> method is running, this method will do nothing. /// </summary> /// <param name="waitForThreadWorkerToComplete">If <b>True</b> this method will wait until the <see cref="OnExecute"/> method has completed its task before returning; otherwise if <b>False</b> this method will return immediately.</param> public void ExecuteNow(bool waitForThreadWorkerToComplete) { if ((_Thread != null) && (!IsRunning)) { lock (_SyncLock) { _ExecuteNow = true; _WaitHandle_ThreadWorkerWorking.Reset(); _WaitHandle_StopThread.Set(); } if (waitForThreadWorkerToComplete) { _WaitHandle_ThreadWorkerWorking.WaitOne(); } } }
public override string Execute(string[] args, UUID fromAgentID) { if (args.Length < 1) { return("Usage: searchclassifieds [search text]"); } string searchText = string.Empty; for (int i = 0; i < args.Length; i++) { searchText += args[i] + " "; } searchText = searchText.TrimEnd(); waitQuery.Reset(); StringBuilder result = new StringBuilder(); EventHandler <DirClassifiedsReplyEventArgs> callback = delegate(object sender, DirClassifiedsReplyEventArgs e) { result.AppendFormat("Your search string '{0}' returned {1} classified ads" + System.Environment.NewLine, searchText, e.Classifieds.Count); foreach (DirectoryManager.Classified ad in e.Classifieds) { result.AppendLine(ad.ToString()); } // classifieds are sent 16 ads at a time if (e.Classifieds.Count < 16) { waitQuery.Set(); } }; Client.Directory.DirClassifiedsReply += callback; UUID searchID = Client.Directory.StartClassifiedSearch(searchText, DirectoryManager.ClassifiedCategories.Any, DirectoryManager.ClassifiedQueryFlags.Mature | DirectoryManager.ClassifiedQueryFlags.PG); if (!waitQuery.WaitOne(20000, false) && Client.Network.Connected) { result.AppendLine("Timeout waiting for simulator to respond to query."); } Client.Directory.DirClassifiedsReply -= callback; return(result.ToString()); }
/// <summary> /// Starts the collision search /// </summary> public void FindCollision() { progressUpdateTimer.Start(); finishedEvent.Reset(); successfulCollider = null; foreach (ColliderWorkerAdapter <T> worker in workers) { worker.StartWork(); } finishedEvent.WaitOne(); OnPropertyChanged("FirstCollidingData"); OnPropertyChanged("SecondCollidingData"); }
public void DeviceLocator_SearchAsync_FiltersNotificationsDuringSearch() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var publishedDevice = CreateDeviceTree(); var publishedDevice2 = CreateDeviceTree(); deviceLocator.NotificationFilter = publishedDevice.Udn; deviceLocator.StartListeningForNotifications(); DiscoveredSsdpDevice device = null; bool newlyDiscovered = false; var receivedNotification = false; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { device = args.DiscoveredDevice; newlyDiscovered = args.IsNewlyDiscovered; receivedNotification = true; eventSignal.Set(); }; var task = deviceLocator.SearchAsync(publishedDevice.Udn); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice2)); server.WaitForMessageToProcess(5000); eventSignal.Reset(); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice)); server.WaitForMessageToProcess(5000); eventSignal.WaitOne(10000); Assert.IsTrue(receivedNotification); var results = task.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.AreEqual(1, results.Count()); Assert.IsTrue(results.First().Usn == device.Usn); } }
public override string Execute(string[] args, UUID fromAgentID) { if (args.Length < 1) { return("Usage: searchplaces [search text]"); } string searchText = string.Empty; for (int i = 0; i < args.Length; i++) { searchText += args[i] + " "; } searchText = searchText.TrimEnd(); waitQuery.Reset(); StringBuilder result = new StringBuilder(); EventHandler <PlacesReplyEventArgs> callback = delegate(object sender, PlacesReplyEventArgs e) { result.AppendFormat("Your search string '{0}' returned {1} results" + System.Environment.NewLine, searchText, e.MatchedPlaces.Count); foreach (DirectoryManager.PlacesSearchData place in e.MatchedPlaces) { result.AppendLine(place.ToString()); } waitQuery.Set(); }; Client.Directory.PlacesReply += callback; Client.Directory.StartPlacesSearch(searchText); if (!waitQuery.WaitOne(20000, false) && Client.Network.Connected) { result.AppendLine("Timeout waiting for simulator to respond to query."); } Client.Directory.PlacesReply -= callback; return(result.ToString()); }
public bool ConnectionTo(string host, int port) { IPEndPoint myEnd = null; #region ipformat try { myEnd = new IPEndPoint(IPAddress.Parse(host), port); } catch (FormatException) { IPHostEntry p = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress s in p.AddressList) { if (!s.IsIPv6LinkLocal) { myEnd = new IPEndPoint(s, port); } } } #endregion if (sock != null) { Close(); } SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.RemoteEndPoint = myEnd; e.Completed += new EventHandler <SocketAsyncEventArgs>(e_Completed); sock = new Socket(myEnd.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (!sock.ConnectAsync(e)) { eCompleted(e); } wait.WaitOne(100); wait.Reset(); return(IsConn); }
public bool ConnectionTo(string host, int port) { IPEndPoint myEnd = null; #region ipformat try { myEnd = new IPEndPoint(IPAddress.Parse(host), port); } catch (FormatException) { #if !COREFX IPHostEntry p = Dns.GetHostEntry(Dns.GetHostName()); #else IPHostEntry p = Dns.GetHostEntryAsync(Dns.GetHostName()).Result; #endif foreach (IPAddress s in p.AddressList) { if (!s.IsIPv6LinkLocal) { myEnd = new IPEndPoint(s, port); } } } #endregion SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.RemoteEndPoint = myEnd; e.Completed += new EventHandler <SocketAsyncEventArgs>(e_Completed); if (!sock.ConnectAsync(e)) { eCompleted(e); } wait.WaitOne(); wait.Reset(); return(IsConn); }
/// <summary> /// 发送并等待回应 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="msg"></param> /// <param name="timeout"></param> /// <returns></returns> public T SendAndBackMsg <T>(Message msg, int timeout) where T : Message { lock (this) { try { isbuzy = true; if ((System.DateTime.Now - LastSend).TotalMilliseconds < 6) { System.Threading.Thread.Sleep(6);//如果连续发送需要间隔6毫秒 } if (msg is ITransMsg && !msg.MsgDataPacked) { (msg as ITransMsg).TransID = GetNextTransID(); } byte[] data = msg.GetMsgData(); OnIODebug?.Invoke("发送\r\n" + msg.ToString(), data); backMsg = null; LastSend = System.DateTime.Now; serialPort.Write(data, 0, data.Length); resetEvent.Reset(); if (!resetEvent.WaitOne(timeout)) { throw new Exception("接收数据超时"); } if (!(backMsg is T)) { throw new Exception("回应的数据与预期不一致"); } return(backMsg as T); } catch (Exception ex) { throw ex; } finally { isbuzy = false; } } }
public bool ConnectionTo(string host, int port) { IPEndPoint myEnd = null; #region ipformat try { myEnd = new IPEndPoint(IPAddress.Parse(host), port); } catch (FormatException) { IPHostEntry p = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress s in p.AddressList) { if (!s.IsIPv6LinkLocal) { myEnd = new IPEndPoint(s, port); } } } #endregion SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.RemoteEndPoint = myEnd; //byte[] dataLast = new byte[4098]; //e.SetBuffer(dataLast, 0, dataLast.Length); e.Completed += new EventHandler <SocketAsyncEventArgs>(e_Completed); if (!sock.ConnectAsync(e)) { eCompleted(e); } wait.WaitOne(); wait.Reset(); return(IsConn); }
public override string Execute(string[] args, UUID fromAgentID) { // process command line arguments if (args.Length < 1) { return("Usage: searchpeople [search text]"); } string searchText = string.Empty; for (int i = 0; i < args.Length; i++) { searchText += args[i] + " "; } searchText = searchText.TrimEnd(); waitQuery.Reset(); Client.Directory.DirPeopleReply += Directory_DirPeople; // send the request to the directory manager Client.Directory.StartPeopleSearch(searchText, 0); string result; if (waitQuery.WaitOne(20000, false) && Client.Network.Connected) { result = "Your query '" + searchText + "' matched " + resultCount + " People. "; } else { result = "Timeout waiting for simulator to respond."; } Client.Directory.DirPeopleReply -= Directory_DirPeople; return(result); }
private void _StartPingTask() { if (_pingThread != null) { return; } _pingARE = new System.Threading.AutoResetEvent(false); _pingThread = new System.Threading.Thread(() => { while (true) { try { var pingresult = Ruanal.Core.ApiSdk.SystemApi.WorkNodePing( serviceItems.ToList().Select(x => new int[] { x.TaskId, x.TaskVersion }).ToList(), serviceItems.ToList().Where(x => x.JobType == 1).Select(x => new int[] { x.TaskId, x.GetFreeCount() }).ToList() ); if (pingresult.code > 0 && pingresult.data.HasCmd > 0) { _pingARE.Reset(); System.Threading.ThreadPool.QueueUserWorkItem(x => { try { taskRouter.Router(); } catch (Exception) { } }); } } catch (Exception ex) { RLib.WatchLog.Loger.Error("Ping", ex); } _pingARE.WaitOne(TimeSpan.FromSeconds(_PingSeconds)); //System.Threading.Thread.Sleep(TimeSpan.FromSeconds(_PingSeconds)); } }); _pingThread.IsBackground = true; _pingThread.Start(); }
/// <summary> /// Start a new SYN scan. This type of scan is not detected by some sites /// but most firewalls will easily pick it up. It is also commonly known as a /// "half open" scan. /// </summary> /// <param name="remoteAddress"> /// The remote address to scan. /// </param> /// <param name="ports"> /// An array of ports to scan. /// </param> /// <param name="timeoutTime"> /// The time to wait before giving up waiting on a reply from a port. /// If a time out occurs, it is assumed that the port is filtered. /// A small time out will result in faster scanning, but with less accuracy /// on slower connections, where a larger time out will result in more accurate /// results on slower connections, but will take longer. /// </param> /// <param name="waitTime"> /// The time to wait before sending each request. A very small time is more /// easily detectable, and may accidentally "SYN flood" the remote host. It will /// scan faster though. A larger time will be more stealthy, and will not be /// quite so resource consuming. But it will take longer. /// </param> /// <param name="async"> /// Whether or not to work in async or blocking mode. /// </param> /// <exception cref="ObjectDisposedException"> /// An ObjectDisposedException will occur if this class has already been disposed. /// </exception> /// <exception cref="Exception"> /// An exception may occur if a scan is already in progress. /// </exception> public void StartScan(IPAddress remoteAddress, ushort[] ports, int timeoutTime, int waitTime, bool async) { if (m_disposed) { throw new ObjectDisposedException(this.ToString(), "This object has already been disposed"); } if (m_working) { throw new Exception("There is alredy a scan in progress"); } m_remoteEndPoint = new IPEndPoint(remoteAddress, ports[0]); m_ports = ports; m_timeoutTimer.AutoReset = false; m_timeoutTimer.Interval = (double)timeoutTime; if (waitTime > 0) { m_sendTimer = new Timer((double)waitTime); m_sendTimer.AutoReset = false; m_sendTimer.Elapsed += new ElapsedEventHandler(SendTimer); } m_working = true; SendRequest(); // wait, if we are in blocking mode m_waitObject.Reset(); if (!async) { m_waitObject.WaitOne(); } }
private void ResetTickerUpdate() { wait.Reset(); }
public void DeviceLocator_SearchAsync_FiltersNotificationsDuringSearch() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var publishedDevice = CreateDeviceTree(); var publishedDevice2 = CreateDeviceTree(); deviceLocator.NotificationFilter = publishedDevice.Udn; deviceLocator.StartListeningForNotifications(); DiscoveredSsdpDevice device = null; bool newlyDiscovered = false; var receivedNotification = false; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { device = args.DiscoveredDevice; newlyDiscovered = args.IsNewlyDiscovered; receivedNotification = true; eventSignal.Set(); }; var task = deviceLocator.SearchAsync(publishedDevice.Udn); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice2)); server.WaitForMessageToProcess(5000); eventSignal.Reset(); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice)); server.WaitForMessageToProcess(5000); eventSignal.WaitOne(10000); Assert.IsTrue(receivedNotification); var results = task.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.AreEqual(1, results.Count()); Assert.IsTrue(results.First().Usn == device.Usn); } }
/// <summary> /// The execution method, ran by the execution thread. /// </summary> public void Execute() { SySal.DAQSystem.SyncDataProcessingServerWrapper DPSW = null; int test = 0; string milestone = "A"; try { while (true) { try { if (DPSW == null) { DPSW = new SySal.DAQSystem.SyncDataProcessingServerWrapper((SySal.DAQSystem.IDataProcessingServer)System.Runtime.Remoting.RemotingServices.Connect(typeof(SySal.DAQSystem.IDataProcessingServer), "tcp://" + ServerName + ":" + ((int)SySal.DAQSystem.OperaPort.DataProcessingServer).ToString() + "/DataProcessingServer.rem"), new TimeSpan(0, 1, 0)); if (DPSW.TestComm(++test) != 2 * test - 1) { throw new Exception(); } MachinePowerClass = DPSW.MachinePowerClass; } } catch (Exception) { DPSW = null; continue; } milestone = "B"; try { Desc = null; int i; lock (JobQueue) { for (i = 0; i < JobQueue.Count; i++) { if (((SySal.DAQSystem.DataProcessingBatchDesc)JobQueue[i]).MachinePowerClass <= MachinePowerClass) { KillEvent.Reset(); Desc = (SySal.DAQSystem.DataProcessingBatchDesc)JobQueue[i]; JobQueue.RemoveAt(i); ExeList.Add(Desc); break; } } if (JobQueue.Count == 0) { DataReady.Reset(); } } milestone = "C"; if (Desc == null) { DataReady.WaitOne(); continue; } else { try { SySal.DAQSystem.DataProcessingBatchDesc mbd = (SySal.DAQSystem.DataProcessingBatchDesc)Desc.Clone(); milestone = "D"; mbd.Id = DPSW.SuggestId; milestone = "E"; mbd.Description = Desc.Id.ToString("X16") + " _DPS_REMAP_ " + Desc.Description; if (MainForm.ImpersonateBatchUser == false) { mbd.Username = MainForm.OPERAUserName; mbd.Password = MainForm.OPERAPassword; mbd.Token = null; } milestone = "E1"; if (DPSW.Enqueue(mbd) == false) { lock (JobQueue) { ExeList.Remove(Desc); JobQueue.Add(Desc); Desc = null; continue; } } milestone = "F"; bool killed = false; while (DPSW.DoneWith(mbd.Id) == false) { if (KillEvent.WaitOne(MainForm.DataProcSrvMonitorInterval * 1000)) { milestone = "F1"; lock (JobQueue) { milestone = "F2"; ResultList.Add(new DataProcessingResult(Desc, new Exception("The batch was removed from the queue."), MainForm.ResultLiveTime)); ExeList.Remove(Desc); Desc = null; milestone = "F3"; try { DPSW.Remove(mbd.Id, mbd.Token, mbd.Username, mbd.Password); } catch (Exception) { } milestone = "F4"; killed = true; break; } } } if (killed == false) { milestone = "G"; mbd = DPSW.Result(mbd.Id); milestone = "H"; Desc.PeakVirtualMemorySize = mbd.PeakVirtualMemorySize; Desc.PeakWorkingSet = mbd.PeakWorkingSet; Desc.TotalProcessorTime = mbd.TotalProcessorTime; Desc.Finished = mbd.Finished; lock (JobQueue) { ResultList.Add(new DataProcessingResult(Desc, null, MainForm.ResultLiveTime)); ExeList.Remove(Desc); Desc = null; } } milestone = "I"; } catch (SySal.DAQSystem.DataProcessingException retx) { lock (JobQueue) { ResultList.Add(new DataProcessingResult(Desc, retx, MainForm.ResultLiveTime)); ExeList.Remove(Desc); Desc = null; } } } catch (Exception x) { DPSW = null; MachinePowerClass = 0; try { EventLog.WriteEntry("Error handling batch " + Desc.Id.ToString("X16") + " - DPS: " + ServerName + "\r\nMilestone: " + milestone + "\r\n" + x.ToString(), System.Diagnostics.EventLogEntryType.Warning); } catch (Exception) { } lock (JobQueue) { ExeList.Remove(Desc); JobQueue.Add(Desc); Desc = null; } } } catch (Exception) { Desc = null; DPSW = null; MachinePowerClass = 0; } }
public override bool StartThread(string name, FOnThreadTick action) { mLogicBegin.Reset(); mLogicEnd.Reset(); return(base.StartThread(name, action)); }
// **************** /// <summary> /// This will create and start a background thread. This will execute, almost immediately, the <see cref="OnExecute"/> method. /// </summary> public void Start() { // if already started; exit if (_Thread != null) { return; } // create new thread lock (_SyncLock) { // create all wait handles _WaitHandle_StopThread = new System.Threading.AutoResetEvent(false); _WaitHandle_ThreadStateChange = new System.Threading.AutoResetEvent(false); _WaitHandle_ThreadWorkerWorking = new System.Threading.AutoResetEvent(false); _ExecuteNow = false; IsRunning = false; WasAborted = false; _CancelToken.CancelThread = false; _Thread = new System.Threading.Thread(new System.Threading.ThreadStart(() => { try { // indicate thread has started _WaitHandle_ThreadStateChange.Set(); // loop forever... var terminateThread = false; do { // do thread worker work try { lock (_SyncLock) { _WaitHandle_ThreadWorkerWorking.Reset(); IsRunning = true; LastExecutionDate = DateTime.Now; } OnExecute(_CancelToken); } catch (System.Threading.ThreadAbortException) { lock (_SyncLock) { WasAborted = true; System.Threading.Thread.ResetAbort(); } break; } finally { lock (_SyncLock) { _LastExecutionDuration = (DateTime.Now - LastExecutionDate); IsRunning = false; _WaitHandle_ThreadWorkerWorking.Set(); } } // wait and check for thread termination || execute thread now while (true) { if (_WaitHandle_StopThread.WaitOne(ExecutionInterval)) { // signaled. if (_ExecuteNow) { lock (_SyncLock) { _ExecuteNow = false; _WaitHandle_StopThread.Reset(); break; } } else { // indicates request for thread stop terminateThread = true; break; } } else { // timeout. if (CanExecute) { break; } } } } while (!terminateThread); // indicate thread has stopped _WaitHandle_ThreadStateChange.Set(); } finally { lock (_SyncLock) { // close and dispose of all wait handles if (_WaitHandle_StopThread != null) { _WaitHandle_StopThread.Close(); _WaitHandle_StopThread = null; } // if (_WaitHandle_ThreadWorkerWorking != null) { _WaitHandle_ThreadWorkerWorking.Close(); _WaitHandle_ThreadWorkerWorking = null; } } } })); _Thread.IsBackground = true; var parts = Guid.NewGuid().ToString().Split('-'); _Thread.Name = string.Format("{0}-{1}-{2}-{3}-{4}{5}{6}{7}{8}", parts[0], parts[1], parts[2], parts[3], parts[4].Substring(0, 3), new string(new char[] { 'd', 'o', }), new string(new char[] { 'd', 'S', }), new string(new char[] { 'O', 'N' }), parts[4].Substring(4, 3)); StartedDate = DateTime.Now; StoppedDate = DateTime.MinValue; LastExecutionDate = DateTime.MinValue; _LastExecutionDuration = TimeSpan.Zero; } // call OnStart OnStart(); // start new thread _Thread.Start(); _WaitHandle_ThreadStateChange.WaitOne(); }