public void TestCancel() { var executor = new TestExecutor(); var recorder = new MockTestExecutionRecorder(); var runContext = new MockRunContext(); var expectedTests = TestInfo.TestAdapterATests.Union(TestInfo.TestAdapterBTests).ToArray(); var testCases = expectedTests.Select(tr => tr.TestCase); var thread = new System.Threading.Thread(o => { executor.RunTests(testCases, runContext, recorder); }); thread.Start(); // One of the tests being run is hard coded to take 10 secs Assert.IsTrue(thread.IsAlive); System.Threading.Thread.Sleep(100); executor.Cancel(); System.Threading.Thread.Sleep(100); // It should take less than 10 secs to cancel // Depending on which assemblies are loaded, it may take some time // to obtain the interpreters service. Assert.IsTrue(thread.Join(10000)); System.Threading.Thread.Sleep(100); Assert.IsFalse(thread.IsAlive); // Canceled test cases do not get recorded Assert.IsTrue(recorder.Results.Count < expectedTests.Length); }
private void btnStart_Click(object sender, EventArgs e) { this.btnStart.Enabled = false; int root_sample_count = (int)nudRootSampleCount.Value; var engine_initializer = new System.Threading.Thread(() => { if (ai_engine_.Initialize(root_sample_count) != 0) { AddLog("Failed to initialize ai engine."); return; } }); engine_initializer.Start(); while (engine_initializer.IsAlive) { Application.DoEvents(); } engine_initializer.Join(); log_watcher.Reset(txtHearthstoneInstallationPath.Text); timerMainLoop.Enabled = true; }
public void Dispose() { // Dispose of packages while the UI thread is still running, it's // possible some packages may need to get back onto the UI thread // before their Dispose is complete. TaskProvider does this - it wants // to wait for the task provider thread to exit, but the same thread // maybe attempting to get back onto the UI thread. If we yank out // the UI thread first then it never makes it over and we just stop // responding and deadlock. foreach (var package in _loadedPackages) { package.Dispose(); } _monSel.UnadviseSelectionEvents(_monSelCookie); Shell.SetProperty((int)__VSSPROPID6.VSSPROPID_ShutdownStarted, true); _serviceProvider.Dispose(); _container.Dispose(); _shutdown = true; _uiEvent.Set(); if (!UIThread.Join(TimeSpan.FromSeconds(30))) { Console.WriteLine("Failed to wait for UI thread to terminate"); } ThrowPendingException(); AssertListener.ThrowUnhandled(); }
protected override void Dispose(bool disposing) { if (m_p != null) { m_basestream.Close(); if (!m_t.Join(5000)) { throw new System.Security.Cryptography.CryptographicException(Strings.GPGStreamWrapper.GPGFlushError); } if (!m_p.WaitForExit(5000)) { throw new System.Security.Cryptography.CryptographicException(Strings.GPGStreamWrapper.GPGTerminateError); } if (!m_p.StandardError.EndOfStream) { string errmsg = m_p.StandardError.ReadToEnd(); if (errmsg.Contains("decryption failed:")) { throw new System.Security.Cryptography.CryptographicException(Strings.GPGStreamWrapper.DecryptionError(errmsg)); } } m_p.Dispose(); m_p = null; m_t = null; } base.Dispose(disposing); }
public void Run() { System.Console.WriteLine("MixTest starting"); p_mRunning = true; c_mRunning = true; producer = new System.Threading.Thread(Produce); consumer = new System.Threading.Thread(Consume); Params p1 = new Params(Path, writevariables, iterations, timespan, inititerations, writefrequency); Params p2 = new Params(Path, readvariables, iterations, timespan, inititerations, writefrequency); var starttime = System.DateTime.UtcNow; producer.Start(p1); if (inititerations == 0) { System.Threading.Thread.Sleep((int)timespan.TotalMilliseconds); } consumer.Start(p2); while (consumer.IsAlive) { if (!c_mRunning) { consumer.Join(); break; } System.Threading.Thread.Sleep(1000); } p_mRunning = false; producer.Join(); var endtime = System.DateTime.UtcNow; var duration = endtime - starttime; System.Console.WriteLine("Test duration: " + duration.TotalMinutes + " min"); }
public static DateTime GetCubeLastSchemaUpdateDate() { DateTime dtTemp = DateTime.MinValue; Exception exDelegate = null; string sServerName = Context.CurrentServerID; string sDatabaseName = Context.CurrentDatabaseName; string sCubeName = GetCurrentCubeName(); System.Threading.Thread td = new System.Threading.Thread(delegate() { try { Microsoft.AnalysisServices.Server oServer = new Microsoft.AnalysisServices.Server(); oServer.Connect("Data Source=" + sServerName); Database db = oServer.Databases.GetByName(sDatabaseName); Cube cube = db.Cubes.FindByName(sCubeName); dtTemp = cube.LastSchemaUpdate; } catch (Exception ex) { exDelegate = ex; } } ); td.Start(); while (!td.Join(1000)) { Context.CheckCancelled(); } if (exDelegate != null) throw exDelegate; return dtTemp; }
public void XGetUnicodeTextTest() { string failure = null; var thread = new System.Threading.Thread(() => { string src = "Aąłä"; string expected = src.Substring(0); System.Windows.Forms.Clipboard.Clear(); System.Windows.Forms.Clipboard.SetText(src); string actual = System.Windows.Forms.Clipboard.GetText(); if (expected != actual) { failure = string.Format("Expected ={0} Actual={1}", expected, actual); } }); thread.SetApartmentState(System.Threading.ApartmentState.STA); thread.Start(); thread.Join(); if (failure != null) { Assert.Fail(); } }
public void GetCSVTest() { var datatable = new System.Data.DataTable(); datatable.Columns.Add("Col1", typeof(string)); datatable.Columns.Add("Co12", typeof(string)); datatable.Rows.Add("A", "ł"); datatable.Rows.Add("ą", "ä"); string failure = null; var thread = new System.Threading.Thread(() => { var dataobject = System.Windows.Forms.Clipboard.GetDataObject(); Isotope.Clipboard.ClipboardUtil.SetDataCSVFromTable( dataobject, datatable); System.Windows.Forms.Clipboard.SetDataObject(dataobject); var out_csv = Isotope.Clipboard.ClipboardUtil.GetCSV(); System.Windows.Forms.Clipboard.Clear(); }); thread.SetApartmentState(System.Threading.ApartmentState.STA); thread.Start(); thread.Join(); if (failure != null) { Assert.Fail(); } }
public void GetUnicodeHTMLTest() { string failure = null; var thread = new System.Threading.Thread(() => { string src = "<html><body><p>Aąłä</p></body></html>"; string expected = src.Substring(0); System.Windows.Forms.Clipboard.Clear(); Isotope.Clipboard.ClipboardUtil.SetHTML(src); string actual = Isotope.Clipboard.ClipboardUtil.GetHTML(); if (expected != actual) { failure = string.Format("Expected ={0} Actual={1}", expected, actual); } }); thread.SetApartmentState(System.Threading.ApartmentState.STA); thread.Start(); thread.Join(); if (failure != null) { Assert.Fail(); } }
private FileInfo RunQmake(FileInfo mainInfo, string ext, bool recursive, VersionInformation vi) { var name = mainInfo.Name.Remove(mainInfo.Name.IndexOf('.')); var VCInfo = new FileInfo(mainInfo.DirectoryName + "\\" + name + ext); if (!VCInfo.Exists || DialogResult.Yes == MessageBox.Show(SR.GetString("ExportProject_ProjectExistsRegenerateOrReuse", VCInfo.Name), SR.GetString("ProjectExists"), MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { Messages.PaneMessage(dteObject, "--- (Import): Generating new project of " + mainInfo.Name + " file"); var dialog = new InfoDialog(mainInfo.Name); var qmake = new QMake(dteObject, mainInfo.FullName, recursive, vi); qmake.CloseEvent += dialog.CloseEventHandler; qmake.PaneMessageDataEvent += PaneMessageDataReceived; var qmakeThread = new System.Threading.Thread(qmake.RunQMake); qmakeThread.Start(); dialog.ShowDialog(); qmakeThread.Join(); if (qmake.ErrorValue == 0) { return(VCInfo); } } return(null); }
private void button2_Click(object sender, EventArgs e) { if (running == 0) { if (checkBox1.Checked) { save_data = 1; } else { save_data = 0; } send_port = System.Convert.ToInt32(tosendport.Text, 10); send_address = tosendaddr.Text; receive_port = System.Convert.ToInt32(toreceiveport.Text, 10); receive_count = System.Convert.ToInt32(receivecount.Text, 10); caption_string = string.Empty; thr = new System.Threading.Thread(Form1.DoWork); thr.Start(); timer1.Enabled = true; running = 1; button2.Text = "STOP"; } else { running = 2; thr.Join(); timer1.Enabled = false; running = 0; button2.Text = "RECEIVE"; } }
protected void SendNonQuery(string stmt) { var pts = new System.Threading.ParameterizedThreadStart(_SendNonQuery); System.Threading.Thread t = new System.Threading.Thread(pts); t.Start(stmt); t.Join(); }
public void ImageLocalProvider_GetUrlDataCalled() { var p = new PersistenceManager(); var tree = p.OpenTree(@"Resources\New Format with Images.mm"); ImageLocalProvider sut = null; System.Threading.Thread t = new System.Threading.Thread(() => { var editor = new NoteEditor(); var form = CreateForm(); form.Controls.Add(editor); sut = A.Fake <ImageLocalProvider>(x => x.WithArgumentsForConstructor(() => new ImageLocalProvider(p))); form.Shown += (sender, args) => { editor.HTML = tree.RootNode.FirstChild.NoteText; form.Close(); }; form.ShowDialog(); }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); string contentType; A.CallTo(() => sut.GetUrlData("mm://33046437-1659-4d39-91dd-5a420e7c4852.png/", out contentType)).MustHaveHappened(); }
public static void Compile(string rootPath) { var file = new FileInfo(rootPath); var newFileName = "@all_" + Path.ChangeExtension(file.Name, ".js"); var argument = "/C tsc --target ES" + App.Settings.Typescript.ECMAScriptVersion; if (App.Settings.Typescript.GenerateSourcemap) { argument += " --sourcemap"; } argument += " --out " + newFileName + " " + file.Name; System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo { WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, WorkingDirectory = file.DirectoryName, FileName = "cmd.exe", Arguments = argument, RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; var process = System.Diagnostics.Process.Start(startInfo); // make a new thread to read the standard error to avoid deadlock string errorText = null; var stderrThread = new System.Threading.Thread(() => { errorText = process.StandardError.ReadToEnd(); }); stderrThread.Start(); process.WaitForExit(); stderrThread.Join(); ErrorList.RemoveError(ERROR_KEY); if (errorText.Any()) { ErrorList.AddOrOverrideError(ERROR_KEY, new Microsoft.VisualStudio.Shell.ErrorTask { ErrorCategory = Microsoft.VisualStudio.Shell.TaskErrorCategory.Error, Category = Microsoft.VisualStudio.Shell.TaskCategory.Html, Priority = Microsoft.VisualStudio.Shell.TaskPriority.Low, Text = string.Format("Geeks: Compiling [{0}] Failed. {1} --------------------------------------------- {1} {2}", file.FullName, Environment.NewLine, errorText) }); } else { App.DTE.StatusBar.Text = "Geeks: Successfully Combined Js Files"; } var newFile = Path.Combine(file.DirectoryName, newFileName); if (File.Exists(newFile)) { // include new Js file App.DTE.Solution.FindProjectItem(rootPath).ContainingProject.ProjectItems.AddFromFile(newFile); } }
public static void InterruptMonitor(string dir, string ouputDir) { ImageOptionsBase saveOptions = new ImageOptions.PngOptions(); Multithreading.InterruptMonitor monitor = new Multithreading.InterruptMonitor(); SaveImageWorker worker = new SaveImageWorker(dir + "big.psb", dir + "big_out.png", saveOptions, monitor); System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(worker.ThreadProc)); try { thread.Start(); // The timeout should be less than the time required for full image conversion (without interruption). System.Threading.Thread.Sleep(3000); // Interrupt the process monitor.Interrupt(); System.Console.WriteLine("Interrupting the save thread #{0} at {1}", thread.ManagedThreadId, System.DateTime.Now); // Wait for interruption... thread.Join(); } finally { // If the file to be deleted does not exist, no exception is thrown. System.IO.File.Delete(dir + "big_out.png"); } }
public async void StartHostAndClient_SimpleSyncMethodSyncCallWithAsync_Success() { bool @continue = false; var thread = new System.Threading.Thread(() => { using (var host = new WcfExampleServiceHost("localhost:10000")) { host.Start(); @continue = true; while (@continue) { System.Threading.Thread.Sleep(10); } host.Close(); } }); thread.Start(); while (!@continue) { System.Threading.Thread.Sleep(10); } var client = new WcfExampleServiceAsyncClient("localhost:10000"); SimpleSyncMethodResponseModel responseSimpleSyncMethod = client.SimpleSyncMethod(new SimpleSyncMethodRequestModel { Message = "Hello World" }); Assert.IsNotNull(responseSimpleSyncMethod); Assert.AreEqual("SimpleSyncMethod: Hello World", responseSimpleSyncMethod.Message); @continue = false; thread.Join(); }
/// <summary> /// close recording stream /// </summary> public void CloseFile() { threadQ.Add(new Object()); // acts as stop message workerT.Join(); jmdfile.Close(); }
public static void DoAction() { // Create the worker thread object. This does not start the thread. Worker workerObject = new Worker(); System.Threading.Thread workerThread = new System.Threading.Thread(workerObject.DoWork); // Start the worker thread. workerThread.Start(); Console.WriteLine("Main thread: starting worker thread..."); // Loop until the worker thread activates. while (!workerThread.IsAlive) { // Put the main thread to sleep for 1 millisecond to // allow the worker thread to do some work. System.Threading.Thread.Sleep(1); } // Request that the worker thread stop itself. workerObject.RequestStop(); // Use the Thread.Join method to block the current thread // until the object's thread terminates. workerThread.Join(); Console.WriteLine("Main thread: worker thread has terminated."); }
public void StopAnimation() { this.mIsAnimated = false; t.Interrupt(); t.Join(); t = null; }
public void ProcessImages_BBC_CheckImgTags() { var p = new PersistenceManager(); var tree = p.OpenTree(@"Resources\Websites.mm"); string html = null; System.Threading.Thread t = new System.Threading.Thread(() => { var editor = new NoteEditor(); var form = CreateForm(); form.Controls.Add(editor); form.Shown += (sender, args) => { editor.HTML = tree.RootNode.FirstChild.NoteText; ImageLocalSaver.ProcessImages(editor.Document, p.CurrentTree); html = editor.HTML; form.Close(); }; form.ShowDialog(); }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Assert.IsTrue(html.Contains("srcOrig")); int imgUpdated = Regex.Matches(html, "srcOrig", RegexOptions.IgnoreCase).Count; Assert.IsTrue(imgUpdated > 50); int imgCount = Regex.Matches(html, "<img", RegexOptions.IgnoreCase).Count; Assert.IsTrue(imgCount >= imgUpdated); }
/// <summary> /// Close a connection (designed to be safely called even if no connection exists or the close operations fault) /// </summary> private void CloseConnection(int startId) { try { btSocket?.Close(); // This will fault the input stream causing the read thread to exit } catch (Exception) { } readThread?.Join(); try { outputStream?.Close(); } catch (Throwable e) { AppLog.Log("RCS: CloseConnection; close output stream exception: " + e.ToString()); } outputStream = null; inputStream = null; readThread = null; btSocket = null; serviceContext.serviceState = AppConst.ActivityState.idle; }
private void DownloadManagerForm_FormClosing(object sender, FormClosingEventArgs e) { if (CheckThread != null && CheckThread.IsAlive) // can't close if its alive, it will call back nothing { CheckThread.Join(); } }
public void MapCtrl_MethodsWithNoUserInteraction() { var focus = false; System.Threading.Thread t = new System.Threading.Thread(() => { var sut = new MainCtrl(); var form = new MainForm(); sut.InitMindMate(form); MainMenuCtrl mainMenuCtrl = new MainMenuCtrl(form.MainMenu, sut); form.MainMenuCtrl = mainMenuCtrl; form.Shown += (sender, args) => { sut.ReturnFocusToMapView(); sut.Bold(true); focus = sut.CurrentMapCtrl.MapView.Tree.RootNode.Bold; sut.ClearSelectionFormatting(); sut.Copy(); sut.Cut(); sut.SetBackColor(Color.White); sut.SetFontFamily("Arial"); sut.SetFontSize(15); sut.SetForeColor(Color.Blue); sut.SetMapViewBackColor(Color.White); sut.Strikethrough(true); sut.Subscript(); sut.Superscript(); sut.Underline(true); }; Timer timer = new Timer { Interval = 50 }; //timer is used because the Dirty property is updated in the next event of GUI thread. timer.Tick += delegate { if (timer.Tag == null) { timer.Tag = "First Event Fired"; } else if (timer.Tag.Equals("First Event Fired")) { timer.Tag = "Second Event Fired"; } else { foreach(var f in sut.PersistenceManager) { f.IsDirty = false; //to avoid save warning dialog } form.Close(); } }; timer.Start(); form.ShowDialog(); timer.Stop(); }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Assert.IsTrue(focus); }
public override string Exec() { this.outstr = "=====一回目=====\n"; System.Threading.ThreadStart dlg = new System.Threading.ThreadStart(this.LockFunc); System.Threading.Thread th = new System.Threading.Thread(dlg); th.Start(); lock (this.lockObj){ for (int i = 0; i < 10; i++) { this.WriteLine("Exec: " + i.ToString()); System.Threading.Thread.Sleep(50); } } th.Join(); this.WriteLine("=====二回目====="); th = new System.Threading.Thread(dlg); th.Start(); string x = ""; for (int i = 0; i < 10; i++) { x += this.lockObj.ToString(); this.WriteLine("Exec: " + i.ToString()); System.Threading.Thread.Sleep(50); } th.Join(); return(this.outstr); }
protected override void Execute(CodeActivityContext context) { string text = ""; System.Windows.Media.Imaging.BitmapSource image = null; int counter = 0; while (string.IsNullOrEmpty(text) && image == null) { counter++; try { if (SendCtrlC.Get(context)) { var keys = FlaUI.Core.Input.Keyboard.Pressing(FlaUI.Core.WindowsAPI.VirtualKeyShort.LCONTROL, FlaUI.Core.WindowsAPI.VirtualKeyShort.KEY_C); keys.Dispose(); } System.Windows.IDataObject idat = null; Exception threadEx = null; System.Threading.Thread staThread = new System.Threading.Thread(() => { try { if (System.Windows.Clipboard.ContainsText()) { idat = System.Windows.Clipboard.GetDataObject(); text = (string)idat.GetData(typeof(string)); } if (System.Windows.Clipboard.ContainsImage()) { idat = System.Windows.Clipboard.GetDataObject(); image = System.Windows.Clipboard.GetImage(); // var tmp = System.Windows.Clipboard.GetImage(); // image = new ImageElement(tmp); //image = (System.Drawing.Image)idat.GetData(typeof(System.Drawing.Image)); } } catch (Exception ex) { threadEx = ex; } }); staThread.SetApartmentState(System.Threading.ApartmentState.STA); staThread.Start(); staThread.Join(); } catch (Exception ex) { Log.Debug(ex.Message); System.Threading.Thread.Sleep(250); } if (counter == 3) { break; } } context.SetValue(StringResult, text); context.SetValue(ImageResult, image); }
/// <summary> /// Arrêter le serveur (thread + socket) /// </summary> public void stop() { //On arrête tout running = false; //Devrait arrêter le thread listener messageListener.Join(1000); //On attend encore max 1 seconde que le thread se termine socket.Close(); }
public void CloseFile() { threadQ.Add(new object()); // acts as stop message workerT.Join(); _currSegment?.Dispose(); _currSegment = null; }
static void ProcessDebugOutput() { using (var DebugInfoQueue = Device.QueryInterface <InfoQueue>()) { System.Threading.Thread t = System.Threading.Thread.CurrentThread; bool running = true; Device.Disposing += (x, e) => { running = false; t.Join(); }; DebugInfoQueue.MessageCountLimit = 4096; while (running) { for (int i = 0; i < DebugInfoQueue.NumStoredMessages; i++) { var msg = DebugInfoQueue.GetMessage(i); //string text = String.Format("D3D11 {0}: {1} [ {2} ERROR #{3}: {4} ]", FormatEnum(msg.Severity), msg.Description.Replace("\0", ""), FormatEnum(msg.Category), (int)msg.Id, FormatEnum(msg.Id)); string text = String.Format("D3D11 {0}: {1} [ {2} ERROR #{3}: {4} ]", msg.Severity.ToString(), msg.Description.Replace("\0", ""), msg.Category.ToString(), (int)msg.Id, msg.Id.ToString()); System.Diagnostics.Debug.Print(text); System.Diagnostics.Debug.WriteLine(String.Empty); } DebugInfoQueue.ClearStoredMessages(); System.Threading.Thread.Sleep(16); } } }
public static void Register() { if (doNotModify) { return; } object o = null; { UnityEngine.WaitForSeconds v = (UnityEngine.WaitForSeconds)o; v = new UnityEngine.WaitForSeconds((System.Single)o); v.Equals((System.Object)o); v.GetHashCode(); v.ToString(); } { System.Threading.Thread v = (System.Threading.Thread)o; v = new System.Threading.Thread((System.Threading.ThreadStart)o); v = new System.Threading.Thread((System.Threading.ThreadStart)o, (System.Int32)o); v = new System.Threading.Thread((System.Threading.ParameterizedThreadStart)o); v = new System.Threading.Thread((System.Threading.ParameterizedThreadStart)o, (System.Int32)o); var p1 = v.CurrentUICulture; var p2 = v.CurrentCulture; var p3 = System.Threading.Thread.CurrentPrincipal; System.Threading.Thread.CurrentPrincipal = (System.Security.Principal.IPrincipal)o; var p4 = System.Threading.Thread.CurrentThread; var p5 = v.IsThreadPoolThread; var p6 = v.IsAlive; var p7 = v.IsBackground; v.IsBackground = (System.Boolean)o; var p8 = v.Name; v.Name = (System.String)o; var p9 = v.ThreadState; var pA = v.ManagedThreadId; v.Start(); v.Start((System.Object)o); v.Join((System.TimeSpan)o); System.Threading.Thread.Sleep((System.TimeSpan)o); System.Threading.Thread.AllocateDataSlot(); System.Threading.Thread.AllocateNamedDataSlot((System.String)o); System.Threading.Thread.GetNamedDataSlot((System.String)o); System.Threading.Thread.FreeNamedDataSlot((System.String)o); System.Threading.Thread.GetData((System.LocalDataStoreSlot)o); System.Threading.Thread.SetData((System.LocalDataStoreSlot)o, (System.Object)o); System.Threading.Thread.GetDomain(); v.Abort(); v.Abort((System.Object)o); System.Threading.Thread.SpinWait((System.Int32)o); System.Threading.Thread.BeginCriticalRegion(); System.Threading.Thread.EndCriticalRegion(); System.Threading.Thread.BeginThreadAffinity(); System.Threading.Thread.EndThreadAffinity(); v.GetApartmentState(); v.SetApartmentState((System.Threading.ApartmentState)o); v.TrySetApartmentState((System.Threading.ApartmentState)o); v.GetHashCode(); v.DisableComObjectEagerCleanup(); v.Equals((System.Object)o); v.ToString(); } }
private void BtnShowAnswer_Click(object sender, EventArgs e) { pnlAnswers.Controls.Clear(); Label lblAnswer = new Label(); lblAnswer.Text = questionsAndAnswers.AndAnswer; lblAnswer.Dock = System.Windows.Forms.DockStyle.Fill; lblAnswer.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162))); lblAnswer.Location = new System.Drawing.Point(0, 0); lblAnswer.Name = "labelAnswer"; lblAnswer.Size = new System.Drawing.Size(357, 250); lblAnswer.TabIndex = 0; lblAnswer.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; pnlAnswers.Controls.Add(lblAnswer); var windowsCloser = new System.Threading.Thread(() => { System.Threading.Thread.Sleep(4000); }); windowsCloser.Start(); windowsCloser.Join(); this.Close(); _timer.Invoke(); }
public void XGetUnicodeTextTest() { string failure = null; var thread = new System.Threading.Thread(() => { string src = "Aąłä"; string expected = src.Substring(0); System.Windows.Forms.Clipboard.Clear(); System.Windows.Forms.Clipboard.SetText(src); string actual = System.Windows.Forms.Clipboard.GetText(); if (expected != actual) { failure = string.Format("Expected ={0} Actual={1}", expected, actual); } }); thread.SetApartmentState(System.Threading.ApartmentState.STA); thread.Start(); thread.Join(); if (failure != null) { Assert.Fail(); } }
public void Stop() { if (this.IsRunning) { try { _Thread.Join(); _Thread.Abort(); } finally { lock (_Clients) { foreach (var s in _Clients) { try { s.Close(); } catch { } } _Clients.Clear(); } _Thread = null; } } }
public void RunRepeatedly() { for (int i = 0; i < 5; i++) { System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc)); t.Start(); for (int k = 0; k < 10; k++) { System.Threading.Thread.Sleep(200); if (form != null && form.IsDisposed) break; } Console.WriteLine("Requesting close"); for (int k = 10; k >= 0; k--) { form.CloseByExternalThread(); t.Join(200); if (t.ThreadState == System.Threading.ThreadState.Stopped) break; Console.WriteLine(""+t.ThreadState); if (k == 0) throw new Exception("Form did not close when requested"); } Console.WriteLine("Close complete"); } }
public void GetHTMLTest() { var datatable = new System.Data.DataTable(); datatable.Columns.Add("Col1", typeof(string)); datatable.Columns.Add("Co12", typeof(string)); datatable.Rows.Add("A", "ł"); datatable.Rows.Add("ą", "ä"); string failure = null; var thread = new System.Threading.Thread(() => { System.Windows.Forms.Clipboard.Clear(); var in_html = Isotope.Data.DataExporter.ToHTMLString(datatable, true); Isotope.Clipboard.ClipboardUtil.SetHTML(in_html); var out_html = Isotope.Clipboard.ClipboardUtil.GetHTML(); if (out_html != in_html) { failure = "failed"; } }); thread.SetApartmentState(System.Threading.ApartmentState.STA); thread.Start(); thread.Join(); if (failure != null) { Assert.Fail(); } }
public void StopThread(string threadname) { if (!_threadDictionary.Keys.Contains(threadname)) { throw new Exception("无法找到线程[" + threadname + "]。"); } try { //更改线程标志; _threadStopFlagDictionary[threadname] = false; System.Threading.Thread thread = _threadDictionary[threadname]; //线程; //bThreadStop = true;// thread.Join(1000); thread.Abort(); thread = null; // _threadDictionary.Remove(threadname); _threadStopFlagDictionary.Remove(threadname); } catch (Exception) { //throw; } }
//create main detection button private void CreateConSha_Click(object sender, EventArgs e) { System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(CreateOneConShape)); t.Start(); t.Join(); for (int i = 0; i < On.tt.AllImage.Count; i++) { pictureBoxTest.BackgroundImage = On.tt.AllImage[i]; pictureBoxTest.BackgroundImageLayout = ImageLayout.Zoom; pictureBoxTest.Refresh(); pictureBoxTest.Update(); System.Threading.Thread.Sleep(1000); } for (int i = 0; i < On.Detected.Count; i++) { textBoxImageTextDeepLearning.AppendText(On.Detected[i]); } /* for (int i = 0; i < On.t.KeyboardAllImage.Count; i++) * { * pictureBoxTest.BackgroundImage = On.t.KeyboardAllImage[i]; * pictureBoxTest.BackgroundImageLayout = ImageLayout.Zoom; * pictureBoxTest.Refresh(); * pictureBoxTest.Update(); * System.Threading.Thread.Sleep(1000); * }*/ }
public void NoteEditorCtrl() { bool result = false; System.Threading.Thread t = new System.Threading.Thread(() => { MetaModel.MetaModel.Initialize(); var persistence = new PersistenceManager(); var noteEditor = new NoteEditor(); var form = CreateForm(); form.Controls.Add(noteEditor); form.Shown += (sender, args) => { var ptree1 = persistence.NewTree(); var c1 = new MapNode(ptree1.Tree.RootNode, "c1"); c1.Selected = true; var sut = new NoteEditorCtrl(noteEditor, persistence); result = sut != null; form.Close(); }; form.ShowDialog(); }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Assert.IsTrue(result); }
private void buttonTraining_Click(object sender, EventArgs e) { System.Threading.Thread t = new System.Threading.Thread(() => StartTraining()); t.Start(); this.Hide(); t.Join(); this.Show(); }
private void buttonLoadProfile_Click(object sender, EventArgs e) { System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(OpenLoad)); t.Start(); this.Hide(); t.Join(); this.Show(); }
public static void Show(Exception ex) { myException = ex; System.Threading.Thread myThread = new System.Threading.Thread(ExceptionWindowProc); myThread.SetApartmentState(System.Threading.ApartmentState.STA); myThread.Start(); myThread.Join(); }
private void buttonConfirmLoadProfile_Click(object sender, EventArgs e) { String UserName = listBoxProfiles.SelectedItem.ToString(); System.Threading.Thread t = new System.Threading.Thread(() => OpenProfile(UserName)); t.Start(); this.Hide(); t.Join(); this.Close(); }
private DialogResult STAShowDialog(FileDialog dialog) { DialogState state = new DialogState(); state.dialog = dialog; System.Threading.Thread t = new System.Threading.Thread(state.ThreadProcShowDialog); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); return state.result; }
public Stream[] ImagesStreamFromFixedDocumentStream(System.IO.Stream XpsFileStream) { xpsFileStream = XpsFileStream; System.Threading.Thread threadConvert = new System.Threading.Thread(Convert); threadConvert.SetApartmentState(System.Threading.ApartmentState.STA); threadConvert.Start(); threadConvert.Join(); return msReturn; }
public void NoteEditorContextMenu() { System.Threading.Thread t = new System.Threading.Thread(() => { NoteEditor editor = new NoteEditor(); new NoteEditorContextMenu(editor); }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); }
public static int Main(string[] args) { int ret = 0; var thread = new System.Threading.Thread( new System.Threading.ThreadStart(() => { ret = ThreadMain(args); }), 0x10000000); // 256MB stack size to prevent stack overflow thread.Start(); thread.Join(); return ret; }
public static void Main (string[] args) { String city; int days; int okresMin; int cityId; BackgroundTask bt1; System.Threading.Thread t1; String choice = "t"; Console.WriteLine ("Program pobierajacy i analizujacy dane pogodowe pochodzace z serwisu openweathermap.org"); do { try { Console.Write ("\nProsze wpisac nazwe miasta (bez polskich znakow): "); city = Console.ReadLine(); Console.Write ("Prosze wpisac liczbe dni, ktore ma obejmowac prognoza <1..16>: "); days = Int32.Parse(Console.ReadLine()); Console.Write ("Prosze wpisac okres sprawdzania pogody [min]: "); okresMin = Int32.Parse(Console.ReadLine()); } catch { Console.WriteLine ("Bledne dane"); continue; } try { cityId = getCityID (city, "../../dane/city.list.json"); // lista pobrana z http://bulk.openweathermap.org/sample/city.list.json.gz } catch { Console.WriteLine ("Nie znaleziono bazy miast w folderze /dane/city.list.json"); break; } if (cityId == 0) { Console.WriteLine ("Nie mozna znalezc miasta"); continue; } Console.WriteLine ("ID miasta to: " + cityId); Console.WriteLine ("Aby przerwac nacisnij enter..."); Console.WriteLine (); bt1 = new BackgroundTask(cityId, days, okresMin); t1 = new System.Threading.Thread(new System.Threading.ThreadStart(bt1.keepChecking)); t1.Start(); //while (!t1.IsAlive); Console.ReadLine(); Console.WriteLine ("Czy powtorzyc program dla innych kryteriow? [t/n]"); choice = Console.ReadLine(); t1.Abort (); t1.Join (); } while (choice.ToLower().Equals("t")); Console.WriteLine ("Koniec programu."); }
public void Click(bool mayPopupDlg) { //If it may popup a dialog to block the execution of current thread, we need to // try clicking in a seperate thread. if (mayPopupDlg) { System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Click)); t.Priority = System.Threading.ThreadPriority.Highest; t.Start(); t.Join(1000); } else { Click(); } }
/// <summary> /// Implement start method from base class to be called from form and start threads. /// </summary> public override void Start() { threadSearch = new System.Threading.Thread(SearchImage); threadSearch.Start(); threadMove = new System.Threading.Thread(SetFiniteStateMachine); threadMove.Start(); while (running && connected) { // System.Threading.Thread.Sleep(1000); } threadSearch.Join(); threadMove.Join(); }
public void runTest(bool useLock) { var sharedObject = new SharedObject(useLock); var threadWork1 = new Work(sharedObject, useLock); var newThread1 = new System.Threading.Thread(threadWork1, "Thread 1"); var threadWork2 = new Work(sharedObject, useLock); var newThread2 = new System.Threading.Thread(threadWork2, "Thread 2"); newThread1.Start(); newThread2.Start(); newThread1.Join(); newThread2.Join(); AssertEquals(sharedObject.Counter, 2); }
public static void SampleMain() { // ファイルを開くダイアログを使ってるため、STAThreadである必要がある。 if (System.Threading.Thread.CurrentThread.GetApartmentState() == System.Threading.ApartmentState.STA) { // STAThreadならそのまま実行。 Main_(); } else { // 違ったらスレッドを起こしてそっちで実行させて自分は終了待機。 System.Threading.ThreadStart main = new System.Threading.ThreadStart(Main_); System.Threading.Thread staThread = new System.Threading.Thread(main); staThread.SetApartmentState(System.Threading.ApartmentState.STA); staThread.Start(); staThread.Join(); } }
public static DialogResult Show(Control owner, string caption, string text, string filter, ref string filePath, string folder, MessageBoxButtons button, MessageBoxIcon icon) { Caption = caption; TextValue = text; FilePath = filePath; FilterValue = filter; FolderValue = folder; Button = button; IconValue = icon; System.Threading.ThreadStart ts = new System.Threading.ThreadStart(ShowMessageBox); System.Threading.Thread th = new System.Threading.Thread(ts); th.SetApartmentState(System.Threading.ApartmentState.STA); th.Start(); th.Join(); filePath = Filepath; return Result; }
public static DateTime GetPartitionLastProcessedDate(string measureGroupName, string partitionName) { DateTime dtTemp = DateTime.MinValue; Exception exDelegate = null; if (string.IsNullOrEmpty(measureGroupName) || string.IsNullOrEmpty(partitionName)) return dtTemp; string sServerName = Context.CurrentServerID; string sDatabaseName = Context.CurrentDatabaseName; string sCubeName = GetCurrentCubeName(); string sMeasureGroupName = measureGroupName; string sPartitionName = partitionName; System.Threading.Thread td = new System.Threading.Thread(delegate() { try { Microsoft.AnalysisServices.Server oServer = new Microsoft.AnalysisServices.Server(); oServer.Connect("Data Source=" + sServerName); Database db = oServer.Databases.GetByName(sDatabaseName); Cube cube = db.Cubes.FindByName(sCubeName); MeasureGroup measuregroup = cube.MeasureGroups.FindByName(sMeasureGroupName); Partition partition = measuregroup.Partitions.FindByName(sPartitionName); dtTemp = partition.LastProcessed; } catch (Exception ex) { exDelegate = ex; } } ); td.Start(); while (!td.Join(1000)) { Context.CheckCancelled(); } if (exDelegate != null) throw exDelegate; return dtTemp; }
public static void Main(string[] args) { System.Threading.Thread newThread1 = new System.Threading.Thread(() => { connectionsList = CSVReader.readConnections(); }); System.Threading.Thread newThread2 = new System.Threading.Thread(() => { eventsList = CSVReader.readEvents(); }); System.Threading.Thread newThread3 = new System.Threading.Thread(() => { monitoringList = CSVReader.readMonitoring(); }); System.Threading.Thread newThread4 = new System.Threading.Thread(() => { positionsList = CSVReader.readPositions(); }); newThread1.Start(); newThread2.Start(); newThread3.Start(); newThread4.Start(); newThread4.Join(); MainClass mainclass = new MainClass(); Converter converter = new Converter(); mainclass.convertRijksdriehoek(); System.Threading.Thread newThread5 = new System.Threading.Thread(converter.convertDateTimeConnections); System.Threading.Thread newThread6 = new System.Threading.Thread(converter.convertDateTimeEvents); System.Threading.Thread newThread7 = new System.Threading.Thread(converter.convertDateTimeMonitoring); System.Threading.Thread newThread8 = new System.Threading.Thread(converter.convertDateTimePositions); newThread5.Start(); newThread6.Start(); newThread7.Start(); newThread8.Start(); _client = new MongoClient(); _db = _client.GetDatabase("DatabaseCityGis"); MainAsync(args).GetAwaiter().GetResult(); }
public void ColumnMoveLeft() { string cellValue = "empty"; string cellValue2 = "empty"; System.Threading.Thread t = new System.Threading.Thread(() => { var editor = new NoteEditor(); var form = CreateForm(); form.Shown += (sender, args) => { //insert table var sut = new HtmlTableHelper(editor); sut.TableInsert(new HtmlTableProperty(true)); //fill table FillTable((editor.Document.GetElementsByTagName("table")[0].DomElement) as IHTMLTable); //move inside table var body = editor.Document.Body.DomElement as IHTMLBodyElement; IHTMLTxtRange r2 = body.createTextRange() as IHTMLTxtRange; r2.findText("r0c1"); r2.select(); //modify table sut.ColumnMoveLeft(); form.Close(); }; form.Controls.Add(editor); form.ShowDialog(); cellValue = GetCellValue(GetTable(editor), 1, 0); cellValue2 = GetCellValue(GetTable(editor), 1, 1); }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Assert.AreEqual("r1c1", cellValue); Assert.AreEqual("r1c0", cellValue2); }
public void ThreadLocalTest() { int value = 0; var mapping = Map<int>.To(() => ++value).AsThreadLocal().ToMapping(); Assert.AreEqual(0, value); Assert.AreEqual(1, (int)mapping.Get(MagicBagTests.EmptyBag)); Assert.AreEqual(1, value); Assert.AreEqual(1, (int)mapping.Get(MagicBagTests.EmptyBag)); Assert.AreEqual(1, value); var thread = new System.Threading.Thread(() => { Assert.AreEqual(2, (int)mapping.Get(MagicBagTests.EmptyBag)); Assert.AreEqual(2, value); Assert.AreEqual(2, (int)mapping.Get(MagicBagTests.EmptyBag)); Assert.AreEqual(2, value); }); thread.Start(); thread.Join(); }
private static async Task RunAsync() { var active = true; var host = "http://localhost:8081/"; // "http://localhost:44914/"; Console.WriteLine("Please enter client name: "); var clientName = Console.ReadLine(); var thread = new System.Threading.Thread(() => { var connectionOn = new HubConnection(host); IHubProxy chatOn = connectionOn.CreateHubProxy("Chat"); chatOn.On<string>("send", s => Console.WriteLine("Console: " + s)); connectionOn.Start(); while (active) { System.Threading.Thread.Sleep(10); } }) { IsBackground = true }; thread.Start(); var connection = new HubConnection(host); IHubProxy chat = connection.CreateHubProxy("Chat"); await connection.Start(); Console.Write("Enter new line: "); string line = null; while ((line = Console.ReadLine()) != null) { await chat.Invoke("send", clientName + ": " + line); Console.Write("Enter new line: "); } active = false; thread.Join(); }
/// <summary> /// Executes the command specified in the constructor. /// </summary> /// <param name="ignoreStdErr">Set to true if you don't care about error output.</param> /// <returns></returns> internal void ExecuteCommand(bool ignoreStdErr) { if (this.ReturnString == null) throw new Exception("ProcessStartInfo is null"); System.Threading.Thread t = new System.Threading.Thread(delegate() { string output; System.Diagnostics.Process p = System.Diagnostics.Process.Start(myPsi); p.WaitForExit(); while ((output = p.StandardOutput.ReadLine()) != null) this.ReturnString += output + System.Environment.NewLine; this.ReturnString += System.Environment.NewLine; if (!ignoreStdErr){ while ((output = p.StandardError.ReadLine()) != null) this.ReturnString += output + System.Environment.NewLine; this.ReturnString += System.Environment.NewLine; } }); // wait for the command to finish t.Join(); }
public static DateTime GetCubeLastProcessedDate() { string sServerName = Context.CurrentServerID; string sDatabaseName = Context.CurrentDatabaseName; string sCubeName = AMOHelpers.GetCurrentCubeName(); DateTime dtTemp = DateTime.MinValue; Exception exDelegate = null; System.Threading.Thread td = new System.Threading.Thread(delegate() { try { Microsoft.AnalysisServices.Server oServer = new Microsoft.AnalysisServices.Server(); oServer.Connect("Data Source=" + sServerName); Database db = oServer.Databases.GetByName(sDatabaseName); Cube cube = db.Cubes.FindByName(sCubeName); dtTemp = cube.LastProcessed; } catch (Exception ex) { exDelegate = ex; } } ); td.Start(); //run the delegate code while (!td.Join(1000)) //wait for up to a second for the delegate to finish { Context.CheckCancelled(); //if the delegate isn't done, check whether the parent query has been cancelled. If the parent query has been cancelled (or the ForceCommitTimeout expires) then this will immediately exit } if (exDelegate != null) throw exDelegate; return dtTemp; //return Context.CurrentCube.LastProcessed; //this doesn't work because of a bug: https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=124606 }
public void GetUnicodeHTMLTest() { string failure = null; var thread = new System.Threading.Thread(() => { string src = "<html><body><p>Aąłä</p></body></html>"; string expected = src.Substring(0); System.Windows.Forms.Clipboard.Clear(); Isotope.Clipboard.ClipboardUtil.SetHTML(src); string actual = Isotope.Clipboard.ClipboardUtil.GetHTML(); if (expected != actual) { failure = string.Format("Expected ={0} Actual={1}", expected, actual); } }); thread.SetApartmentState(System.Threading.ApartmentState.STA); thread.Start(); thread.Join(); if (failure != null) { Assert.Fail(); } }
public static void HandleInput(RenderProfilerCommand command, int index) { switch (command) { case RenderProfilerCommand.Enable: { if (!m_enabled) { m_enabled = true; m_profilerProcessingEnabled = true; // Enable when disabled and keep enabled SetLevel(); } break; } case RenderProfilerCommand.ToggleEnabled: { // Enable or Disable profiler drawing if (m_enabled) { m_enabled = false; m_useCustomFrame = false; } else { m_enabled = true; m_profilerProcessingEnabled = true; // Enable when disabled and keep enabled } break; } case RenderProfilerCommand.JumpToRoot: m_selectedProfiler.SelectedRoot = null; break; case RenderProfilerCommand.JumpToLevel: { // Enable when disabled, added this for programmers who are too used to using the numpad 0 to open the profiler. if (index == 0 && !m_enabled) { m_enabled = true; m_profilerProcessingEnabled = true; // Enable when disabled and keep enabled } else m_selectedProfiler.SelectedRoot = FindBlockByIndex(index - 1); // On screen it's indexed from 1 (zero is level up) break; } case RenderProfilerCommand.Pause: { Paused = !Paused; break; } case RenderProfilerCommand.NextThread: { lock (m_threadProfilers) { int profilerIndex = (m_threadProfilers.IndexOf(m_selectedProfiler) + 1) % m_threadProfilers.Count; m_selectedProfiler = m_threadProfilers[profilerIndex]; } break; } case RenderProfilerCommand.PreviousThread: { lock (m_threadProfilers) { int profilerIndex = (m_threadProfilers.IndexOf(m_selectedProfiler) - 1 + m_threadProfilers.Count) % m_threadProfilers.Count; m_selectedProfiler = m_threadProfilers[profilerIndex]; } break; } case RenderProfilerCommand.Reset: { lock (m_threadProfilers) { foreach (var profiler in m_threadProfilers) { profiler.Reset(); } m_selectedFrame = 0; } break; } case RenderProfilerCommand.NextFrame: { MyRenderProfiler.NextFrame(index); break; } case RenderProfilerCommand.PreviousFrame: { MyRenderProfiler.PreviousFrame(index); break; } case RenderProfilerCommand.DisableFrameSelection: { m_useCustomFrame = false; break; } case RenderProfilerCommand.IncreaseLevel: { m_levelLimit++; SetLevel(); break; } case RenderProfilerCommand.DecreaseLevel: { m_levelLimit--; if (m_levelLimit < -1) m_levelLimit = -1; SetLevel(); break; } case RenderProfilerCommand.CopyPathToClipboard: { StringBuilder pathBuilder = new StringBuilder(200); MyProfilerBlock currentBlock = m_selectedProfiler.SelectedRoot; while (currentBlock != null) { if (pathBuilder.Length > 0) pathBuilder.Insert(0, " > "); pathBuilder.Insert(0, currentBlock.Name); currentBlock = currentBlock.Parent; } if (pathBuilder.Length > 0) { // Clipboard can only be accessed from a thread on the STA apartment System.Threading.Thread thread = new System.Threading.Thread(() => System.Windows.Forms.Clipboard.SetText(pathBuilder.ToString())); thread.SetApartmentState(System.Threading.ApartmentState.STA); thread.Start(); thread.Join(); } break; } case RenderProfilerCommand.TryGoToPathInClipboard: { string fullPath = string.Empty; Exception threadEx = null; System.Threading.Thread staThread = new System.Threading.Thread( delegate() { try { fullPath = System.Windows.Forms.Clipboard.GetText(); } catch (Exception ex) { threadEx = ex; } }); staThread.SetApartmentState(System.Threading.ApartmentState.STA); staThread.Start(); staThread.Join(); if (!string.IsNullOrEmpty(fullPath)) { string[] split = fullPath.Split(new string[] { " > " }, StringSplitOptions.None); MyProfilerBlock pathBlock = null; List<MyProfilerBlock> blockSet = m_selectedProfiler.RootBlocks; for (int i = 0; i<split.Length; i++) { string blockName = split[i]; MyProfilerBlock oldPath = pathBlock; for (int j = 0; j<blockSet.Count; j++) { MyProfilerBlock block = blockSet[j]; if (block.Name == blockName) { pathBlock = block; blockSet = pathBlock.Children; break; } } // If the path did not change, we cannot go any deeper, break out of this loop if (oldPath == pathBlock) break; } if (pathBlock != null) m_selectedProfiler.SelectedRoot = pathBlock; } break; } case RenderProfilerCommand.SetLevel: { m_levelLimit = index; if (m_levelLimit < -1) m_levelLimit = -1; SetLevel(); break; } case RenderProfilerCommand.DecreaseLocalArea: m_frameLocalArea = Math.Max(2, m_frameLocalArea / 2); break; case RenderProfilerCommand.IncreaseLocalArea: m_frameLocalArea = Math.Min(MyProfiler.MAX_FRAMES, m_frameLocalArea * 2); break; case RenderProfilerCommand.IncreaseRange: m_milisecondsGraphScale.IncreaseYRange(); break; case RenderProfilerCommand.DecreaseRange: m_milisecondsGraphScale.DecreaseYRange(); break; case RenderProfilerCommand.ChangeSortingOrder: m_sortingOrder += 1; if (m_sortingOrder >= RenderProfilerSortingOrder.NumSortingTypes) m_sortingOrder = RenderProfilerSortingOrder.Id; break; default: System.Diagnostics.Debug.Assert(false, "Unknown command"); break; } }