private void AfterTask(System.Threading.Tasks.Task task, Session s) { if ((((!chunkBuilderFeed.IsCompleted) || chunkBuilderFeed.Count > 0) && !cancellationTokenSource.IsCancellationRequested)) { Logger.Append(Severity.DEBUG, "Asking for another storage session because of expired budget with storage node #" + s.ClientId); User.SendPut(backup.TaskId, s.Id, 1); return; } //unregister storage session for normal chunks Logger.Append(Severity.DEBUG, "Data backup done, ready to process index."); User.StorageSessionReceivedEvent -= new User.StorageSessionReceivedHandler(this.SessionReceived); s.TransfertDoneEvent -= new Session.TransfertDoneHandler(ManageChunkSent); // gracefully disconnect from storage node s.SendDisconnect(); task.Dispose(); //20120729 // if processing chunks is not empty, active sessions finishing transferrring remains, so do nothind /*if(processingChunks.Count > 0 && !cancellationTokenSource.IsCancellationRequested){ * string remainingC = ""; * foreach(BChunk c in processingChunks) * remainingC += " "+c.Name; * Logger.Append(Severity.INFO, processingChunks.Count+" active chunks ("+remainingC+")transfers remaining, not processing index yet..."); * return; * }*/ // stop indexer task }
static IEnumerable<DataSample> _GetBufferedDataFeed(iRacingConnection iRacingConnection, int maxBufferLength) { var que = new ConcurrentQueue<DataSample>(); bool cancelRequest = false; var t = new Task(() => EnqueueSamples(que, iRacingConnection, maxBufferLength, ref cancelRequest)); t.Start(); try { DataSample data; while (true) { if (que.TryDequeue(out data)) yield return data; } } finally { cancelRequest = true; t.Wait(200); t.Dispose(); } }
/// <summary> /// 释放资源 /// </summary> public void Dispose() { TaskList = null; _hasNew = null; cts = null; task.Dispose(); }
public void HandleTcpCom() { Task readerTask = null; Task writerTask = null; try { InfoNode.ConnectionCounter++; Console.WriteLine("{0}. Connection opened.", this._connectionIndex); readerTask = new Task(ReadData); writerTask = new Task(WriteData); writerTask.Start(); readerTask.Start(); Task.WaitAll(new[] { writerTask, readerTask }); } catch (System.IO.IOException exp) { Console.WriteLine("{0}. [Swallow] {1}", this._connectionIndex, exp.Message); } catch (AggregateException exp) { foreach (var exception in exp.InnerExceptions) Console.WriteLine("{0}. [Swallow] {1}", this._connectionIndex, exception.Message); } catch (Exception exp) { Console.WriteLine("{0}. [Throw] {1}", this._connectionIndex, exp.Message); throw; } finally { try { Console.WriteLine("{0}. Ending connection.", this._connectionIndex); InfoNode.ConnectionCounter--; if (_client != null) _client.Close(); //Make sure Task.WaitAll(new[] { writerTask, readerTask }); readerTask.Dispose(); writerTask.Dispose(); Console.WriteLine("{0}. Connection terminated.", this._connectionIndex); } catch (AggregateException exp) { foreach(var exception in exp.InnerExceptions) Console.WriteLine("FATAL EXCEPTION! [Throw] {0}", exception.Message); } catch (Exception exp) { Console.WriteLine("FATAL EXCEPTION! [Throw] {0}", exp.Message); } } }
public void Action(RoomItem Item, Task Task, string ExtraData) { if (ExtraData == "1") { Task.Wait(7000); Item.FireWorkCount--; using (DatabaseClient dbClient = GoldTree.GetDatabase().GetClient()) { dbClient.AddParamWithValue("itemid", Item.uint_0); dbClient.ExecuteQuery("UPDATE items SET fw_count = fw_count - 1 WHERE id = @itemid LIMIT 1"); } } if (Item.FireWorkCount == 0) { ExtraData = "0"; } Item.ExtraData = ExtraData; Item.UpdateState(true, true); Task.Wait(); Task.Dispose(); }
public void Stop() { lock (_lock) { if (_state == State.Running || _state == State.Suspended) { _requestedState = State.Stopped; // Prevent deadlock by checking is we stopping from worker task or not. if (Task.CurrentId != _workerTask.Id) { _eventWaiter.Set(); _workerTask.Wait(); // http://blogs.msdn.com/b/pfxteam/archive/2012/03/25/10287435.aspx // Actually it's not required to call dispose on task, but we will do this if possible. _workerTask.Dispose(); } } else { //throw new InvalidOperationException("The worker is already stopped."); } } }
public void Dispose() { if (_task != null) { _task.Dispose(); _task = null; } }
public void Dispose() { EnqueueTask(null); // 等待当前的工作线程执行完 _worker.Wait(); _worker.Dispose(); // 释放所有资源 _eventWaitHandle.Close(); UnityEngine.Debug.Log("Task over"); }
public static void Dispose_BeforeComplete() { // Verify that a task can only be disposed after it has completed var endTask = new ManualResetEvent(false); var task = new Task(() => { endTask.WaitOne(); }); Assert.Throws<InvalidOperationException>(() => task.Dispose()); task.Start(); Assert.Throws<InvalidOperationException>(() => task.Dispose()); endTask.Set(); task.Wait(); task.Dispose(); Assert.Throws<ObjectDisposedException>(() => { var wh = ((IAsyncResult)task).AsyncWaitHandle; }); // A task may also be disposed after it is canceled endTask.Reset(); var cts = new CancellationTokenSource(); task = new Task(() => { endTask.WaitOne(); }, cts.Token); cts.Cancel(); task.Dispose(); }
public static void Dispose_ThenAddContinuation() { // Verify that a continuation can be added after a task is completed and disposed var task = new Task(() => { }); task.Start(); task.Wait(); task.Dispose(); var task2 = task.ContinueWith(completedTask => { }); task2.Wait(); task2.Dispose(); }
private void SearchClick(object sender, EventArgs e) { try { _view.ClearingFields(); if(_model.SearchResultsList.Count!=0) _model.SearchResultsList.Clear(); UpdateModel(); tokenSource = new CancellationTokenSource(); ct = tokenSource.Token; searchingThread = Task.Factory.StartNew(() => { tokenSource.Token.ThrowIfCancellationRequested(); this.MakeRegexMask(); Regex regMask = new Regex(_model.FileMask, RegexOptions.IgnoreCase); DirectoryInfo di = new DirectoryInfo(_model.Drive); if (!di.Exists) throw new Exception("Выбранный Вами локальный диск не найден или Вам отказано в доступе"); _view.ShowInfoMessage("Поиск начат!"); Searching(di, regMask); int count = _model.SearchResultsList.Count; string endResult; if (_model.IsResults()) endResult = String.Format("Поиск завершен. Найдено {0} файлов", count); else endResult = String.Format("Поиск завершен.По Вашему запросу ничего не найдено"); _view.ShowInfoMessage(endResult); },tokenSource.Token); } catch(Exception ex) { _view.ShowErrorMessage(ex.Message); } finally { if (searchingThread.IsCanceled || searchingThread.IsCompleted || searchingThread.IsFaulted) { searchingThread.Dispose(); tokenSource.Dispose(); } } }
private void UnexpectedError(System.Threading.Tasks.Task task, long taskId) { var aggException = task.Exception.Flatten(); foreach (var exception in aggException.InnerExceptions) { Logger.Append(Severity.CRITICAL, "Unexpected error while processing backup task " + taskId + " : " + exception.Message + " ---- Stacktrace : " + exception.StackTrace); HubWrite("TSK " + taskId + " 899 " + exception.Message); } task.Dispose(); //Backup cur = GetCurrentBackup(taskId); //cur.Terminate(false); currentJobs[taskId].Backup.Terminate(false); BackupDone(currentJobs[taskId].Backup); // rethrow to allow continuations to NOT be processed when they are NotOnFaulted throw new Exception("Propagating unexpected exception..."); }
private void UnexpectedError(System.Threading.Tasks.Task task) { var aggException = task.Exception.Flatten(); foreach (var exception in aggException.InnerExceptions) { Logger.Append(Severity.CRITICAL, "Unexpected error while processing backup task " + this.backup.TaskId + " : " + exception.ToString()); backup.AddHubNotificationEvent(999, exception.Message, ""); } cancellationTokenSource.Cancel(); //theSession.Disconnect(); task.Dispose(); //backup.Terminate(false); // rethrow to allow continuations to NOT be processed when they are NotOnFaulted throw new Exception("Propagating unexpected exception..."); }
private void Work(Task incomingTask) { if (StopHandle.WaitOne(0)) { return; } var evt = EventLoop.NextEvent(); if (evt != null) { Idle = false; _worker = incomingTask.ContinueWith(w2 => evt()); _worker.ContinueWith(Work); } else { Idle = true; } incomingTask.Dispose(); }
public void Start() { //bc = new List<int>(); bc = new BlockingCollection<int>(); Task Pr = new Task(producer); Task Cn = new Task(consumer); Pr.Start(); Cn.Start(); try { Task.WaitAll(Cn, Pr); } finally { Cn.Dispose(); Pr.Dispose(); } }
public void Dispose() { if (_issueListView != null && !_issueListView.IsDisposed && !_issueListView.Disposing) { _issueListView.Dispose(); } _issueListView = null; if (_getWorkItemService != null) { if (_getWorkItemService.Result != null) { _getWorkItemService.Result.Dispose(); } _getWorkItemService.Wait(200); _getWorkItemService.Dispose(); _getWorkItemService = null; } }
/// <inheritdoc /> public void Stop() { if (_cancellationTokenSource != null) { lock (_cancellationTokenSource) { if (!_cancellationTokenSource.IsCancellationRequested) { _cancellationTokenSource.Cancel(); } _cancellationTokenSource?.Dispose(); _cancellationTokenRegistration.Dispose(); _cancellationTokenSource = null; } if (_task != null && _task.Status.In(TaskStatus.RanToCompletion, TaskStatus.Canceled, TaskStatus.Faulted)) { _task.Dispose(); } } }
private static void Listen(int port) { try { Console.WriteLine("Listening for traffic on port {0}.", port); _tcpListener = new TcpListener(IPAddress.Any, port); _tcpListener.Start(); while (_running) { var client = _tcpListener.AcceptTcpClient(); var cmn = new Communicator(client); var tcpHandler = new Task(cmn.HandleTcpCom); _tcpHandlers.Add(tcpHandler); tcpHandler.Start(); } } catch (SocketException exp) { //Closing listener Console.WriteLine("Listener. [Swallow] {0}", exp.Message); } catch (Exception exp) { Console.WriteLine("Listener. [Throw] {0}", exp.Message); throw; } finally { foreach(var tcpHandler in _tcpHandlers) tcpHandler.Dispose(); _tcpListener.Stop(); Console.WriteLine("Stopped listening for traffic on port {0}.", port); } }
private void _load() { List<string> stream_urls = new List<string>(); Status = StreamStatus.Connecting; // Request playlist var gen_req = (HttpWebRequest)HttpWebRequest.Create(_channelListenM3UUrl); gen_req.UserAgent = _userAgent; var gen_resp = (HttpWebResponse)gen_req.GetResponse(); var gen_resp_s = gen_resp.GetResponseStream(); var gen_resp_r = new StreamReader(gen_resp_s); stream_urls.AddRange(from url in gen_resp_r.ReadToEnd().Split('\n') where !url.TrimStart().StartsWith("#") && !string.IsNullOrEmpty(url.Trim()) select url.Trim()); // Go through each URL foreach (string stream_url in stream_urls) { try { if (_cancel_play_token.IsCancellationRequested) break; // Request the stream Console.WriteLine("Connecting to " + stream_url + "..."); var stream_req = (HttpWebRequest)HttpWebRequest.Create(stream_url); stream_req.UserAgent = _userAgent; stream_req.Headers.Add("icy-metadata", "1"); // Request icecast to also send metadata stream_req.Timeout = 3000; stream_req.ReadWriteTimeout = 5000; var stream_resp = stream_req.GetResponse(); // Save stream info var stream_info = new Dictionary<string, string>(); foreach (string key in stream_resp.Headers.AllKeys) if (key.ToLower().StartsWith("ice-") || key.ToLower().StartsWith("icy-")) { stream_info.Add(key.ToLower(), stream_resp.Headers[key]); Console.WriteLine(" " + key.ToLower() + ": " + stream_resp.Headers[key]); } StationInformation = stream_info; // Wait for buffer to initialize properly _buffer(stream_resp.GetResponseStream()); // Start playback try { // Direct buffer for audio _wavebuffer = new BufferedWaveProvider(_decoderMp3.OutputFormat); _wavebuffer.BufferDuration = TimeSpan.FromSeconds(10); // Start buffering and playback _cancel_buffer = new CancellationTokenSource(); _cancel_buffer_token = _cancel_buffer.Token; _bufferThread = Task.Factory.StartNew(() => _bufferLoop(), _cancel_buffer_token); _playThread = Task.Factory.StartNew(() => _play(), _cancel_play_token); Console.WriteLine("Load thread now sleeping, waiting until play thread finishes."); _playThread.Wait(_cancel_buffer_token); } catch (OperationCanceledException) { { } } catch (Exception error) { Console.WriteLine("Load thread error: {0}", error.ToString()); } if (_playThread.Status == TaskStatus.WaitingForChildrenToComplete || _playThread.Status == TaskStatus.Running) { Console.WriteLine("Waiting for playback thread to exit..."); try { _playThread.Wait(); } catch { { } } _playThread.Dispose(); } if (_bufferThread.Status == TaskStatus.WaitingForChildrenToComplete || _bufferThread.Status == TaskStatus.Running) { Console.WriteLine("Waiting for buffering thread to exit..."); _cancel_buffer.Cancel(); try { _bufferThread.Wait(); } catch { { } } _bufferThread.Dispose(); } break; } catch (Exception error) { Console.WriteLine("Can't load stream: {0}", error.ToString()); } } Console.WriteLine("Loading thread work done."); }
static void Main(string[] args) { //Read input parameters var port = _defaultPort; if (args.Length > 0) { if (!int.TryParse(args[0], out port)) port = _defaultPort; } Console.Title = string.Format("Rubicon.ReverseProxy.TcpTestServer port={0}", port); //Start a listener try { var listenerTask = new Task(() => Listen(port)); listenerTask.Start(); Console.WriteLine("Press any key to stop server..."); Console.ReadKey(); _tcpListener.Stop(); _running = false; listenerTask.Wait(); listenerTask.Dispose(); } catch (Exception exp) { Console.WriteLine("Main. [Swallow] {0}", exp.Message); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
private void Cancelled(Task<ACommonData> data) { this.SwitchStopButtonStatus(false); this.LockOrUnlockInterface(false); this.AddToLog("Задание по скачиванию и парсингу страницы было отменено"); this.SetOrAppendMessage(true, "Процесс скачивания и парсинга страницы был успешно отменён"); this.UpdateStatus(6); this.LockOrUnlockFooterButtons(true); data.Dispose(); data = null; }
private void Finished(Task<ACommonData> data) { this.SwitchStopButtonStatus(false); this._parsedItem = data.Result; data.Dispose(); data = null; this.LockOrUnlockInterface(false); this._cancelGrabbingPage.Dispose(); this._cancelGrabbingPage = null; if (this._parsedItem.IsNull() == true) { this.CleanLayout(); this.UpdateStatus(4); return; } else if (this._parsedItem is ParsedAlbum) { this.UpdateStatus(3); this.RenderAlbum((ParsedAlbum)this._parsedItem); this.AddToLog("Данные альбома загружены"); } else { this.UpdateStatus(3); this.RenderSong((ParsedSong)this._parsedItem); this.AddToLog("Данные песни загружены"); } Action a = () => { this.tb_InputURI.Text = this._parsedItem.ItemLink.ToString(); if (this._URI_history.Count > 0) { this.btn_Back.Enabled = true; } }; this.Invoke(a); this._URI_history.Push(this._parsedItem.ItemLink); }
static void RunwithRetry(int retrycount) { if (retrycount == 0) return; const int TimeOut = 300000; var cancel = new CancellationTokenSource(); Task a = new Task(RunCopy, cancel.Token); a.Start(); a.Wait(TimeOut); if(a.Status == TaskStatus.Running) { cancel.Cancel(); a.Dispose(); RunwithRetry(retrycount - 1); } else if(a.Status == TaskStatus.Faulted) { if(a.Exception != null) { throw a.Exception; } } }
//second thread private void StartLoad() { flag = "checkFiles"; InvokeUpdateControls(); task = Task.Factory.StartNew(CheckFiles); task.Wait(); task.Dispose(); flag = "checkConn"; InvokeUpdateControls(); task = Task.Factory.StartNew(CheckConnection); task.Wait(); //task.Dispose(); flag = "fetchSettings"; InvokeUpdateControls(); task = Task.Factory.StartNew(FetchSettings); task.Wait(); task.Dispose(); flag = "checkUpdate"; InvokeUpdateControls(); task = Task.Factory.StartNew(CheckUpdates); task.Wait(); task.Dispose(); flag = "fetchBulletin"; InvokeUpdateControls(); task = Task.Factory.StartNew(FetchBulletin); task.Wait(); task.Dispose(); flag = "success"; InvokeUpdateControls(); task = Task.Factory.StartNew(Finish); task.Wait(); task.Dispose(); }
public virtual bool TryGetResponse(out string response) { string resp = response = null; _ResponseTask = Task.Factory.StartNew(() => { resp = GetResponse(IdleTimeout + ServerTimeout * 3); }); try { if (_ResponseTask.Wait(IdleTimeout)) { response = resp; _ResponseTask.Dispose(); _ResponseTask = null; return true; } else return false; } catch (AggregateException) { throw; } }
private void ExecuteBeginCommand() { recorder = new Recorder(new Test { Project = test.Project }); recorder.ScreenshotsEnabled = false; isActive = true; Window window = new Window(); window.Height = SystemParameters.VirtualScreenHeight; window.Width = SystemParameters.VirtualScreenWidth; bool doPicture = false; Canvas canvas = new Canvas(); Rectangle rectangle = new Rectangle(); rectangle.StrokeThickness = 3; rectangle.Stroke = Brushes.Red; rectangle.Height = 0; rectangle.Width = 0; Ellipse ellipse = new Ellipse(); ellipse.StrokeThickness = 3; ellipse.Stroke = Brushes.Red; ellipse.Width = 0; ellipse.Height = 0; Canvas.SetTop(rectangle, 0); Canvas.SetLeft(rectangle, 0); Canvas.SetTop(ellipse, 0); Canvas.SetLeft(ellipse, 0); UIItem currentUIItem = null; System.Drawing.Point point = new System.Drawing.Point(); Task task = new Task(() => { recorder.Record(); try { while (SelectedTrainingItem != null && isActive) { TestItem testItem = recorder.NewTestItems.LastOrDefault(); if (testItem != null && testItem.Control.Equals(SelectedTrainingItem.TestItem.Control) && SelectedTrainingItem.TestItem.Operation.GetType() == testItem.Operation.GetType() && SelectedTrainingItem.TestItem.Operation is ClickOperation) { AdvanceSelectedTrainingItem(); } else if (SelectedTrainingItem.TestItem.Operation is KeyboardOperation && (SelectedTrainingItem.TestItem.Operation as KeyboardOperation).Text == recorder.CurrentText) { AdvanceSelectedTrainingItem(); } point = System.Windows.Forms.Cursor.Position; AppProcess process = test.Project.AppManager.GetProcess(SelectedTrainingItem.TestItem.Control); MappedItem windowItem = test.Project.AppManager.GetWindow(SelectedTrainingItem.TestItem.Control); IUIItem uiItem = AppPlaybackService.GetControl(process, windowItem, SelectedTrainingItem.TestItem.Control, test.Project.AppManager); //Point clickPoint = this.GetClickPoint(); Rect bounds = uiItem.AutomationElement.Current.BoundingRectangle; //Thread.Sleep(500); Application.Current.Dispatcher.Invoke(new Action(() => { //rectangle.Width = 10; //rectangle.Height = 10; //Canvas.SetTop(rectangle, globalPoint.X - rectangle.Width); //Canvas.SetLeft(rectangle, globalPoint.Y - rectangle.Height); rectangle.Width = bounds.Width; rectangle.Height = bounds.Height; Canvas.SetTop(rectangle, bounds.Y); Canvas.SetLeft(rectangle, bounds.X); })); } } catch (Exception ex) { } recorder.Stop(); }); canvas.Children.Add(rectangle); canvas.Children.Add(ellipse); window.Left = 0; window.Top = 0; window.Content = canvas; window.WindowStyle = new WindowStyle(); window.ShowInTaskbar = false; window.AllowsTransparency = true; window.Background = Brushes.Transparent; window.Topmost = true; window.Show(); task.Start(); task.ContinueWith(t => { Application.Current.Dispatcher.Invoke(new Action(window.Close)); }); window.Closed += (o, args) => { isActive = false; task.Dispose(); }; }
private void ExecuteGetObjectCommand() { testItemController.MinimizeTestItemEditorWindow(); Window window = new Window(); window.Height = SystemParameters.VirtualScreenHeight; window.Width = SystemParameters.VirtualScreenWidth; bool doPicture = false; Canvas canvas = new Canvas(); Rectangle rectangle = new Rectangle(); rectangle.StrokeThickness = 3; rectangle.Stroke = Brushes.Red; rectangle.Height = 0; rectangle.Width = 0; Canvas.SetTop(rectangle, 0); Canvas.SetLeft(rectangle, 0); UIItem currentUIItem = null; System.Drawing.Point point = new System.Drawing.Point(); Task task = new Task(() => { doPicture = true; UIItem prevUIItem = null; GlobalHooker hooker = new GlobalHooker(); KeyboardHookListener listener = new KeyboardHookListener(hooker); listener.Enabled = true; listener.KeyDown += (o, args) => { if (args.Shift && args.Control && args.KeyCode == Keys.A) { doPicture = false; } }; while (doPicture) { point = Cursor.Position; currentUIItem = ExternalAppInfoManager.GetControl(System.Windows.Forms.Cursor.Position); if (currentUIItem.AutomationElement.Current.ProcessId == Process.GetCurrentProcess().Id) currentUIItem = prevUIItem; if (currentUIItem == null) continue; Rect bounds = currentUIItem.AutomationElement.Current.BoundingRectangle; Thread.Sleep(250); Application.Current.Dispatcher.Invoke(new Action(() => { rectangle.Width = bounds.Width; rectangle.Height = bounds.Height; Canvas.SetTop(rectangle, bounds.Y); Canvas.SetLeft(rectangle, bounds.X); })); prevUIItem = currentUIItem; } }); canvas.Children.Add(rectangle); window.Left = 0; window.Top = 0; window.Content = canvas; window.WindowStyle = new WindowStyle(); window.ShowInTaskbar = false; window.AllowsTransparency = true; window.Background = Brushes.Transparent; window.Topmost = true; window.Show(); task.Start(); task.ContinueWith(t => { UIItem = currentUIItem; TestItem onScreenValidation = testItemController.CurrentTestItem; if (onScreenValidation.Operation != null) { OperationParameter operationParameterX = onScreenValidation.Operation.GetParameterNamed("ClientX"); OperationParameter operationParameterY = onScreenValidation.Operation.GetParameterNamed("ClientY"); if (operationParameterX != null && operationParameterY != null) { operationParameterX.Value = point.X - UIItem.Bounds.X; operationParameterY.Value = point.Y - UIItem.Bounds.Y; } } Application.Current.Dispatcher.Invoke(new Action(() => { window.Close(); Thread.Sleep(500); testItemController.RestoreTestItemEditorWindow(); Thread.Sleep(500); testItemController.RestoreTestItemEditorWindow(); })); }); window.Closed += (o, args) => { doPicture = false; task.Dispose(); }; }
public void go_data() { //запускаем заполнение списка using (FbConnection fb = new FbConnection(fc_old.ConnectionString)) { try { fb.Open(); int i_ = 0; int j_ = tables_.Count; foreach (string t_ in tables_) { i_++; p_text = i_.ToString() + "/" + j_.ToString() + " " + t_; //прогресс таблиц p_cur = (int)(((float)i_ / (float)j_) * 100); using (FbTransaction ft = fb.BeginTransaction()) { using (FbCommand fcon = new FbCommand("Select * from " + t_,fb,ft)) { switch (t_.Trim().ToUpper()) { case "DELETED": fcon.CommandText += " where Date_Deleted >= cast('NOW' as date) - 180"; break; case "ERR_LOG": fcon.CommandText += " where id_err_log is null"; break; case "BACKUP_LOG": fcon.CommandText += " where id_BACKUP_LOG is null"; break; case "SHADOWGUARD": fcon.CommandText += " where id_SHADOW is null"; break; case "USER_ACTIVITY": fcon.CommandText += " where id_user_activity is null"; break; case "MESSAGES": fcon.CommandText += " where lastdate >= cast('NOW' as date) - 100"; break; case "SCHEDULER": fcon.CommandText += " where id_status is null"; break; case "USER_CONNECTIONS": fcon.CommandText += " where ID_USER_CONNECTIONS is null"; break; case "REPORT_REPLICATION": fcon.CommandText += " where DATE_CREATE >= cast('NOW' as date) - 30"; break; } using (FbDataReader fr = fcon.ExecuteReader()) { while (fr.Read()) { var sqlinsert = "insert into " + t_ + " values("; for (int t = 0; t <= fr.FieldCount - 1; t++) { if (sqlinsert != "insert into " + t_ + " values(") { sqlinsert += ","; } if (fr[t] == DBNull.Value) { sqlinsert += "null"; } else { if (fr[t].GetType().ToString().ToUpper() == "SYSTEM.DOUBLE") { sqlinsert += fr[t].ToString().Replace(",", "."); } else //заменяем все ' на '' sqlinsert += "'" + fr[t].ToString().Replace("'", "''").Replace(" 0:00:00", " ") + "'"; } } sqlinsert += ");"; q_data.Enqueue(sqlinsert);//добавляем INSERT if (q_data.Count >= 100000) { //запускаем создание записей на базе using (Task t_load = new Task(go_load)) { t_load.Start(); t_load.Wait(); t_load.Dispose(); q_data.Clear(); } } } fr.Dispose(); } fcon.Dispose(); } ft.Commit(); ft.Dispose(); } } //и в конце запустим еще раз using (Task t_load = new Task(go_load)) { t_load.Start(); t_load.Wait(); t_load.Dispose(); q_data.Clear(); } p_text = "Анализ данных завершен"; //конец анализа p_cur = 100; is_close_analize = true;//флаг, что анализ данных завершен } catch (FbException ex) { sb.AppendLine(""); sb.AppendLine(ex.Message); } finally { fb.Close(); } fb.Dispose(); } }
private void TaskStop(ref Task task) { if (task != null) { //if (task.IsCompleted == false || task.Status == TaskStatus.Running || // task.Status == TaskStatus.WaitingToRun || task.Status == TaskStatus.WaitingForActivation) this.autobuff.??; try { if (task.Status == TaskStatus.RanToCompletion || task.Status == TaskStatus.Running || task.Status == TaskStatus.WaitingToRun || task.Status == TaskStatus.WaitingForChildrenToComplete ) task.Dispose(); // some times it's not helps... } catch { ; } } }
internal void Ex_Manager() { LastExClockTick = Environment.TickCount; while(m_GameManager.Ex_ManagerThreadShouldStop==false) { if (m_GameManager.ManagerStatus == typGamestatus.PAUSE_STATUS) { if (GroundExecuteStateTask != null && GroundExecuteStateTask.IsCompleted == false) { try { GroundExecuteStateTask.Wait(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); } catch (AggregateException exx) { // Log.WriteErrorToLog(exx, m_GameManager.curScenario.DbName); } } Thread.Sleep(1000); continue; } else if ((m_GameManager.ManagerStatus == typGamestatus.EDIT_STATUS) || (m_GameManager.ManagerStatus == typGamestatus.PROCESS_RUN2EDIT)) { // Thread.CurrentThread.Abort(); break; } // m_GameManager.ExClockRatioSpeed = 6; if (m_GameManager.ExClockRatioSpeed != 0) { double currExClockTick = Environment.TickCount; double TickCount = currExClockTick - LastExClockTick; // int sleepTime = 1000 / m_GameManager.ExClockRatioSpeed - (int)TickCount; int sleepTime = ExClockResolution / m_GameManager.ExClockRatioSpeed - (int)TickCount; if (sleepTime > 0 && sleepTime < Int32.MaxValue) { Thread.Sleep(sleepTime); } } //int sleepTime = 1000 / m_GameManager.ExClockRatioSpeed - (int)TickCount; //if (sleepTime > 0 && sleepTime < Int32.MaxValue) //{ // Thread.Sleep(sleepTime); //} // ExClockResolution = 1000; Ex_clockDate = Ex_clockDate.AddMilliseconds(ExClockResolution); // Yinon Douchan: Code for statistics and simulation of explosion // update statistics every second if ((Ex_clockStartDate - Ex_clockDate).TotalMilliseconds % 10000 == 0) { collisionData.Add(new CollisionData(Ex_clockDate, totalCollisions, nonFrontalCollisions, frontalCollisions)); } // --------------------------------------------------------------- LastExClockTick = Environment.TickCount; TimeSpan TSGroundExecute = Ex_clockDate.Subtract(Ex_clockGroundExecute); if (TSGroundExecute.TotalMilliseconds >= m_GameManager.GroundCycleResolution) { Ex_clockGroundExecute = Ex_clockDate; if (GroundExecuteStateTask != null) { try { GroundExecuteStateTask.Wait(); GroundExecuteStateTask.Dispose(); GroundExecuteStateTask = null; } catch (AggregateException Exx) { GroundExecuteStateTask.Dispose(); GroundExecuteStateTask = null; // GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); // Log.WriteErrorToLog(Exx, m_GameManager.curScenario.DbName); } } GroundExecuteStateTask = new Task(() => { manageEvents(); foreach (KeyValuePair<string, AtomBase> keyVal in GroundAtomObjectCollection) { clsGroundAtom refGroundAtom = keyVal.Value as clsGroundAtom; refGroundAtom.ExecuteState(); refGroundAtom.CheckCondition(); } NotifyClientsEndCycleArgs args = new NotifyClientsEndCycleArgs(); args = new NotifyClientsEndCycleArgs(); args.Transport2Client.Ex_clockDate = Ex_clockDate; // args.Transport2Client.ExClockRatioSpeed = m_GameManager.ExClockRatioSpeed; args.Transport2Client.AtomObjectType = 2; args.Transport2Client.AtomObjectCollection = PrepareGroundCommonProperty(); args.Transport2Client.ManagerStatus = m_GameManager.ManagerStatus; m_GameManager.NotifyClientsEndCycle(args); } ); GroundExecuteStateTask.Start(); } Thread.Sleep(5); // (10); } }
public WebService Test(string args, Guid workspaceId, Guid dataListId) { var service = new WebService(); try { service = JsonConvert.DeserializeObject<WebService>(args); if(string.IsNullOrEmpty(service.RequestResponse)) { ErrorResultTO errors; ExecuteRequest(service, true, out errors, _webExecute); ((WebSource)service.Source).DisposeClient(); } var preTestRsData = service.Recordsets; service.RequestMessage = string.Empty; service.JsonPathResult = string.Empty; if(service.RequestResponse.IsJSON() && String.IsNullOrEmpty(service.JsonPath)) { service.ApplyPath(); // we need to timeout this request after 10 seconds due to nasty pathing issues ;) Thread jsonMapTaskThread = null; var jsonMapTask = new Task(() => { jsonMapTaskThread = Thread.CurrentThread; service.Recordsets = FetchRecordset(service, true); }); jsonMapTask.Start(); jsonMapTask.Wait(10000); if(!jsonMapTask.IsCompleted) { if(jsonMapTaskThread != null) { jsonMapTaskThread.Abort(); } service.Recordsets = preTestRsData; service.RequestMessage = GlobalConstants.WebServiceTimeoutMessage; } jsonMapTask.Dispose(); } else { service.Recordsets = FetchRecordset(service, true); } } catch(Exception ex) { RaiseError(ex); if(service.Recordsets.Count > 0) { service.Recordsets[0].HasErrors = true; service.Recordsets[0].ErrorMessage = ex.Message; } service.RequestResponse = ex.Message; } return service; }
private void ExecuteSelectImageCommand() { testItemController.MinimizeTestItemEditorWindow(); Window window = new Window(); window.Height = SystemParameters.VirtualScreenHeight; window.Width = SystemParameters.VirtualScreenWidth; bool doPicture = false; Canvas canvas = new Canvas(); canvas.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 100,100,100)); Rectangle rectangle = new Rectangle(); rectangle.StrokeThickness = 2; rectangle.Stroke = Brushes.Red; rectangle.Height = 0; rectangle.Width = 0; Canvas.SetTop(rectangle, 0); Canvas.SetLeft(rectangle, 0); System.Drawing.Point point = new System.Drawing.Point(); GlobalHooker hooker = new GlobalHooker(); MouseHookListener listener = new MouseHookListener(hooker); bool isMouseDown = false; bool isComplete = false; System.Drawing.Point topLeft = new System.Drawing.Point(); System.Drawing.Point bottomRight = new System.Drawing.Point(); listener.MouseDown += (o, args) => { isMouseDown = true; topLeft = System.Windows.Forms.Cursor.Position; }; listener.MouseUp += (o, args) => { isMouseDown = false; bottomRight = System.Windows.Forms.Cursor.Position; isComplete = true; }; listener.Enabled = true; Task task = new Task(() => { listener.Enabled = true; while (!isComplete) { Thread.Sleep(250); while (isMouseDown) { point = System.Windows.Forms.Cursor.Position; Rect bounds = new Rect(new Point(topLeft.X, topLeft.Y), new Point(point.X, point.Y)); Thread.Sleep(100); Application.Current.Dispatcher.Invoke(new Action(() => { rectangle.Width = bounds.Width; rectangle.Height = bounds.Height; Canvas.SetTop(rectangle, bounds.Y); Canvas.SetLeft(rectangle, bounds.X); })); } } }); canvas.Children.Add(rectangle); window.Left = 0; window.Top = 0; window.Content = canvas; window.WindowStyle = new WindowStyle(); window.ShowInTaskbar = false; window.AllowsTransparency = true; Bitmap screenshot = new Bitmap(1,1); BitmapImage bitmapImage = new BitmapImage(); window.Topmost = true; Task waitTask = new Task(() => { Thread.Sleep(3000); Application.Current.Dispatcher.Invoke(new Action(() => { using (MemoryStream memory = new MemoryStream()) { screenshot = Camera.Capture(0, ScreenCaptureMode.Screen); screenshot.Save(memory, ImageFormat.Png); memory.Position = 0; bitmapImage.BeginInit(); bitmapImage.StreamSource = memory; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); } window.Background = new ImageBrush(bitmapImage); window.Show(); })); }); task.ContinueWith(t => { System.Drawing.Rectangle systemRect = new System.Drawing.Rectangle(topLeft.X, topLeft.Y, bottomRight.X-topLeft.X, bottomRight.Y-topLeft.Y); Bitmap tempBitmap = new Bitmap(systemRect.Width, systemRect.Height); using (Graphics g = Graphics.FromImage(tempBitmap)) { g.DrawImage(screenshot, new System.Drawing.Rectangle(0, 0, tempBitmap.Width, tempBitmap.Height), systemRect, GraphicsUnit.Pixel); } Image = tempBitmap; TestItem testItem = testItemController.CurrentTestItem; OperationParameter operationParameter = testItem.Operation.GetParameterNamed("Image"); operationParameter.Value = Image; Application.Current.Dispatcher.Invoke(new Action(() => { window.Close(); Thread.Sleep(500); testItemController.RestoreTestItemEditorWindow(); Thread.Sleep(500); testItemController.RestoreTestItemEditorWindow(); })); }); waitTask.Start(); waitTask.ContinueWith(t => task.Start()); window.Closed += (o, args) => { doPicture = false; task.Dispose(); }; }
private void FreeTask(Task<MailBox> task, ICollection<Task<MailBox>> tasks) { _log.Debug("End Task {0} with status = '{1}'.", task.Id, task.Status); if (!tasks.Remove(task)) _log.Error("Task not exists in tasks array."); ReleaseMailbox(task.Result); task.Dispose(); }
/// <summary> /// Tracks the upload progress in the PowerShell console. /// </summary> /// <param name="uploadTask">The task that tracks the upload.</param> /// <param name="uploadProgress">The upload progress that will be displayed in the console.</param> private void TrackUploadProgress(Task uploadTask, ProgressRecord uploadProgress, Cmdlet commandToUpdateProgressFor, CancellationToken token) { // Update the UI with the progress. var lastUpdate = DateTime.Now.Subtract(TimeSpan.FromSeconds(2)); while (!uploadTask.IsCompleted && !uploadTask.IsCanceled) { if (token.IsCancellationRequested) { // we are done tracking progress and will just break and let the task clean itself up. try { uploadTask.Wait(); } catch (OperationCanceledException) { if (uploadTask.IsCanceled) { uploadTask.Dispose(); } } catch (AggregateException ex) { if (ex.InnerExceptions.OfType<OperationCanceledException>().Any()) { if (uploadTask.IsCanceled) { uploadTask.Dispose(); } } else { throw; } } break; } if (DateTime.Now - lastUpdate > TimeSpan.FromSeconds(1)) { lock (ConsoleOutputLock) { if (commandToUpdateProgressFor != null && !token.IsCancellationRequested && !commandToUpdateProgressFor.Stopping) { commandToUpdateProgressFor.WriteProgress(uploadProgress); } } } TestMockSupport.Delay(250); } if (uploadTask.IsCanceled || token.IsCancellationRequested) { uploadProgress.RecordType = ProgressRecordType.Completed; } else if (uploadTask.IsFaulted && uploadTask.Exception != null) { // If there are errors, raise them to the user. if (uploadTask.Exception.InnerException != null) { // we only go three levels deep. This is the Inception rule. if (uploadTask.Exception.InnerException.InnerException != null) { throw uploadTask.Exception.InnerException.InnerException; } throw uploadTask.Exception.InnerException; } throw uploadTask.Exception; } else { // finally execution is finished, set progress state to completed. uploadProgress.PercentComplete = 100; uploadProgress.RecordType = ProgressRecordType.Completed; if (commandToUpdateProgressFor != null) { commandToUpdateProgressFor.WriteProgress(uploadProgress); } } }
//------------------------------------------------------------------------- private void Completed(Task t) { if (t.Status.ToString() != "RanToCompletion" && t.AsyncState.ToString() != "mainTask") log.LogMessage("___" + "Completed Task : " + t.AsyncState.ToString() + " with Status : " + t.Status.ToString()); RemoveTask(t.AsyncState.ToString()); //if (t.IsCanceled) Log.LogMessage("Recognizing was cancelled"); if (t.Exception != null) { log.LogMessage(t.Exception); } t.Dispose(); GC.Collect(); }
/// <summary> /// Creates a new Log Writter instance /// </summary> /// <param name="FileLocation">The location of the logfile. If the file doesnt exist, /// It will be created.</param> /// <param name="Truncate">If set to true and the logfile is over XX size, it will be truncated to 0 length</param> /// <param name="TruncateLen"> /// If <paramref name="Truncate"/> is true, The size of the file must be at least this size, /// in bytes, to truncate it /// </param> public LogWriter(string FileLocation, bool Truncate = false, int TruncateLen = 2097152) { // Set internals LogFile = new FileInfo(FileLocation); LogQueue = new ConcurrentQueue<LogMessage>(); // Test that we are able to open and write to the file using (FileStream stream = LogFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { // If the file is over 2MB, and we want to truncate big files if (Truncate && LogFile.Length > TruncateLen) { stream.SetLength(0); stream.Flush(); } } // Create our task FlushTask = new Task(FlushLog); // Start a log timer, and auto write new logs every 3 seconds LogTimer = new Timer(3000); LogTimer.Elapsed += (s, e) => { if (LogQueue.Count > 0 && FlushTask.Status != TaskStatus.Running) { // Dispose old instance if (FlushTask.Status != TaskStatus.Created) { // Create new FlushTask.Dispose(); FlushTask = new Task(FlushLog); } // Start the task FlushTask.Start(); } }; LogTimer.Start(); }
//Generates the modulus using more thread private static BigInteger ParGenMod(GeneratorWrap gen, uint wordSize, int threads, uint precision) { IPrime mainGenerator, workerGenerator; //threads distribution for primes creation if (threads < 4) { mainGenerator = new SequentialPrime(gen.GetInt(), precision, wordSize); workerGenerator = new SequentialPrime(gen.GetInt(), precision, wordSize); } else { mainGenerator = new ParallelPrime(gen.GetInt(), precision, wordSize, threads - threads / 2); workerGenerator = new ParallelPrime(gen.GetInt(), precision, wordSize, threads / 2); } //primes creation var firstPrime = gen.GetBig(); var secondPrime = gen.GetBig(); while (!SecurityCheck(firstPrime, secondPrime)) { secondPrime = gen.GetBig(); } Task<BigInteger> worker = new Task<BigInteger>(workerGenerator.NextPrime, firstPrime); worker.Start(); secondPrime = mainGenerator.NextPrime(secondPrime); worker.Wait(); firstPrime = worker.Result; worker.Dispose(); return firstPrime*secondPrime; }
public void DisposeUnstartedTest () { var t = new Task (() => { }); t.Dispose (); }
void OnTaskStopping(Task t, int index) { lock (startJobLock) { taskRunning[index] = 0; curNumberRunningTasks--; t.Dispose(); tasks[index] = null; if (traceEnabled) { lock (totalProcessCountLock) { var curId = queues[index].ID; var curCount = processCounts[curId]; processCounts[curId] = 0; processCounts.Add(Guid.NewGuid(), curCount); } } } // Queue must be empty System.Diagnostics.Debug.Assert(queues[index].Size() == 0); }