public void Teste_MultiThreading() { // Thread Corrente // Thread.CurrentThread.ManagedThreadId; ThreadStart pontoEntrada = new ThreadStart(ExecutarTeste); Thread _thread = new Thread(pontoEntrada); _thread.Name = "Thread principal..."; _thread.Start(); _thread.Suspend(); _thread.Resume(); _thread.Abort(); try { } catch (ThreadAbortException) { throw; } }
static void Main(string[] args) { Console.WriteLine("主线程-创建线程实例"); //创建子线程 Thread thread = new Thread(new ThreadStart(ThreadProc)); Console.WriteLine("主线程-子线程状态:{0}", thread.ThreadState); //启动子线程 Console.WriteLine("主线程调用start方法"); thread.Start(); Console.WriteLine("主线程-子线程状态{0}", thread.ThreadState); Thread.Sleep(5000); Console.WriteLine("主线程-调用suspend方法"); thread.Suspend(); Console.WriteLine("主线程-子线程状态{0}", thread.ThreadState); Thread.Sleep(1000); Console.WriteLine("主线程-调用resume方法"); thread.Resume(); Console.WriteLine("主线程-子线程状态{0}", thread.ThreadState); Thread.Sleep(5000); Console.WriteLine("主线程-调用abort方法"); thread.Abort(); Console.WriteLine("主线程-子线程状态{0}", thread.ThreadState); Console.WriteLine("主线程-调用join方法"); Console.WriteLine("主线程-子线程状态{0}", thread.ThreadState); Console.Read(); }
public void Run() { Thread tA = new Thread( new ThreadStart( ThreadA ) ); Thread tB = new Thread( new ThreadStart( ThreadB ) ); Thread.CurrentThread.Name = "Main thread"; tA.Name = "Thread A"; tB.Name = "Thread B"; tA.Start(); tB.Start(); System.Console.WriteLine( "Suspending thread A" ); Thread.Sleep( 100 ); tA.Suspend(); Thread.Sleep( 2500 ); System.Console.WriteLine( "Suspending thread B" ); tB.Suspend(); Thread.Sleep( 2500 ); System.Console.WriteLine( "Running GC..." ); GC.Collect(); System.Console.WriteLine( "Suspending main thread" ); Thread.Sleep( 2500 ); tA.Resume(); _mreA.Set(); Thread.Sleep( 2500 ); tB.Resume(); _mreB.Set(); }
static void Main(string[] args) { //主线程不需要显示启动 Thread.CurrentThread.Name = "主线程"; Console.WriteLine("主线程启动"); //创建用户线程 Thread thread = new Thread(new ThreadStart(ThreadProc)); //启动用户线程 thread.Start(); //suspend user thread thread.Suspend(); Console.WriteLine("用户线程挂起"); Console.WriteLine(thread.IsAlive); //suspend 5s Thread.Sleep(5000); thread.Resume(); Console.WriteLine("用户线程恢复"); //suspend 5s Thread.Sleep(5000); //结束用户线程 thread.Abort(); thread.Join(); Console.WriteLine("用户线程结束"); Console.Read(); }
static void Main(string[] args) { ThreadStart ts = new ThreadStart(Method); Thread t = new Thread(ts); t.Start(); // Запуск потока. Console.WriteLine("Нажмите любую клавишу для остановки"); Console.ReadKey(); t.Suspend(); // Приостановка потока. Console.WriteLine("Поток остановлен!"); Console.WriteLine("Нажмите любую клавишу для возобновления"); Console.ReadKey(); t.Resume(); // Возобновление работы. }
static void Main(string[] args) { ThreadStart ts = new ThreadStart(Method); Thread t = new Thread(ts); t.Start(); Console.WriteLine("Press any key to stop stream"); Console.ReadKey(); t.Suspend(); Console.WriteLine("Stream stoped"); Console.WriteLine("Press any key to continue stream"); Console.ReadKey(); t.Resume(); }
public static void Main(string[] args) { Console.Write("Diga o nome do arquivo de img: "); string nomeArq = Console.ReadLine(); Console.Write("Diga o tamanho do embacamento: "); int coef = Int32.Parse(Console.ReadLine()); Image imagem = Image.FromFile(nomeArq); Bitmap bitmap = new Bitmap(imagem); Console.Write("Quantas thread horizontais? "); int threadsH = Int32.Parse(Console.ReadLine()); Console.Write("Quantas thread verticais? "); int threadsV = Int32.Parse(Console.ReadLine()); totalThreads = threadsH * threadsV; ThreadEmb[,] threads = new ThreadEmb[threadsV, threadsH]; int i, j; int qtdX = bitmap.Width / threadsH; int qtdY = bitmap.Height / threadsV; Graphics g = Graphics.FromImage(bitmap); for(i = 0; i < threadsV; i++) for (j = 0; j < threadsH; j++) threads[i, j] = new ThreadEmb((Bitmap)bitmap.Clone(), coef, qtdX * j, qtdX, qtdY * i, qtdY, i, j); Thread t; ThreadStart ts; threadPrincipal = Thread.CurrentThread; for (i = 0; i < threadsV; i++) for (j = 0; j < threadsH; j++) { ts = new ThreadStart(threads[i, j].Iniciar); t = new Thread(ts); t.Start(); } //while (threadCompletas < totalThreads) { } threadPrincipal.Suspend(); for (i = 0; i < threadsV; i++) for (j = 0; j < threadsH; j++) threads[i,j].desenhaResultado(g); bitmap.Save("editado_" + nomeArq); }
static void Main() { CharGenerator g1 = new CharGenerator(); CharGenerator g2 = new CharGenerator(); CharGenerator g3 = new CharGenerator(); Thread t1 = new Thread(new ThreadStart(g1.GenerateChar)); Thread t2 = new Thread(new ThreadStart(g2.GenerateChar)); Thread t3 = new Thread(new ThreadStart(g3.GenerateChar)); t1.Start(); t2.Start(); t3.Start(); string input = ""; do { Console.WriteLine("Enter \"try\" when you're ready, \"exit\" to escape"); input = Console.ReadLine(); if (input == "try" || input == "t") { t1.Suspend(); t2.Suspend(); t3.Suspend(); if (g1.ch == g2.ch && g2.ch == g3.ch) { Console.WriteLine(g1.ch + " " + g2.ch + " " + g3.ch + " won"); } else { Console.WriteLine(g1.ch + " " + g2.ch + " " + g3.ch + " lost"); } t1.Resume(); t2.Resume(); t3.Resume(); } Thread.Sleep(100); } while (input != "exit"); g1.end = true; g2.end = true; g3.end = true; return; }
/// <summary> /// http://stackoverflow.com/questions/285031/how-to-get-non-current-threads-stacktrace/14935378#14935378 /// </summary> /// <param name="targetThread"></param> /// <returns></returns> private static StackTrace GetStackTrace(Thread targetThread) { ManualResetEventSlim fallbackThreadReady = new ManualResetEventSlim(); ManualResetEventSlim exitedSafely = new ManualResetEventSlim(); try { new Thread(delegate() { fallbackThreadReady.Set(); if (!exitedSafely.Wait(200)) { try { targetThread.Resume(); } catch (Exception) {/*Whatever happens, do never stop to resume the main-thread regularly until the main-thread has exited safely.*/} } }).Start(); fallbackThreadReady.Wait(); //From here, you have about 200ms to get the stack-trace. targetThread.Suspend(); StackTrace trace = null; try { trace = new StackTrace(targetThread, true); } catch (ThreadStateException) { //failed to get stack trace, since the fallback-thread resumed the thread //possible reasons: //1.) This thread was just too slow //2.) A deadlock ocurred //Automatic retry seems too risky here, so just return null. } try { targetThread.Resume(); } catch (ThreadStateException) {/*Thread is running again already*/} return trace; } finally { //Just signal the backup-thread to stop. exitedSafely.Set(); } }
//중단버튼 눌렀을때 private void button1_Click(object sender, EventArgs e) { DialogResult Result; t1.Suspend(); Result = MessageBox.Show("작업을 중단할까요?", "정지", MessageBoxButtons.YesNo); if (Result == DialogResult.Yes) { this.Exit(); } else { t1.Resume(); } }
public void Start() { System.Threading.Thread work1 = new System.Threading.Thread (WorkA); System.Threading.Thread work2 = new System.Threading.Thread (WorkB); work1.Priority = ThreadPriority.Lowest; work2.Priority = ThreadPriority.Highest; work1.Start(); work2.Start(); work1.Suspend(); Console.ReadLine(); work1.Resume(); Console.ReadLine(); }
/// <summary> /// 报警线程 /// </summary> public void run() { strSend = "正在初始化..."; label1.Text = "正在初始化..."; send(strSend); Thread.Sleep(5000); showBreakRecord(); Thread t1 = new Thread(new ThreadStart(showBadRecord)); t1.IsBackground = true; t1.Start(); while (true) { //-----设置断网信息输出时间间隔----- Thread.Sleep(120000); t1.Suspend(); showBreakRecord(); t1.Resume(); } }
public static ApplicationHangException CreateForThread(Thread thread) { StackTrace tt = null; if (!IsMono) { #if !CORECLR #pragma warning disable 0618 try { thread.Suspend(); } catch { return null; } try { tt = new System.Diagnostics.StackTrace(thread, false); } catch (ThreadStateException) { } try { thread.Resume(); } catch (Exception) { Thread.Sleep(3000); thread.Resume(); } #pragma warning restore 0618 #endif } return new ApplicationHangException( tt, thread.Name ); }
public static StackTrace GetThreadStackTrace(Thread targetThread, bool needFileInfo) { StackTrace stackTrace; if (targetThread == Thread.CurrentThread) // current thread { stackTrace = new StackTrace(needFileInfo); // skip ... frames (reporter stack) } else // other thread { targetThread.Suspend(); try { stackTrace = new StackTrace(targetThread, needFileInfo); } finally { targetThread.Resume(); } } return stackTrace; }
static void Main(string[] args) { Thread thr = new Thread(OnPrint); thr.Name = "Thread Two"; thr.Start(); Thread.Sleep(1000); /*Suspend thread*/ /*When thread suspend no exception. */ thr.Suspend(); Thread.Sleep(1000); if ((thr.ThreadState & ThreadState.Suspended) > 0) thr.Resume(); thr.Join(); /* Thread don't finish. If other thread join it, they can wait and wait forever*/ Console.WriteLine("Main thread terminating"); Console.ReadLine(); }
[Category("NotDotNet")] // On MS, ThreadStateException is thrown on Abort: "Thread is suspended; attempting to abort" public void TestSuspendAbort () { if (is_win32 && is_mono) Assert.Fail ("This test fails on Win32. The test should be fixed."); Thread t = new Thread (new ThreadStart (DoCount)); t.IsBackground = true; t.Start (); CheckIsRunning ("t1", t); t.Suspend (); WaitSuspended ("t2", t); CheckIsNotRunning ("t3", t); t.Abort (); int n=0; while (t.IsAlive && n < 200) { Thread.Sleep (10); n++; } Assert.IsTrue (n < 200, "Timeout while waiting for abort"); CheckIsNotRunning ("t6", t); }
/// <summary> /// Suspends the thread, if the thread is already suspended it has no effect /// </summary> public void Suspend() { threadField.Suspend(); }
public static int main() { // http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201411/20141116 // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201411/20141122 // http://www.sockets.com/winsock.htm#Bind // http://msdn.microsoft.com/en-us/library/wf2w9f6x.aspx Console.WriteLine("20141104 does this device support speaker music?"); // System.Collections.Generic.EqualityComparer`1[<foo>j__TPar] for Boolean Equals(<foo>j__TPar, <foo>j__TPar) used at // LP<>f__AnonymousType0_1 type0_10; var xx = new { foo = "xhello from outer scope" }; // we dont do virtuals yet // yet. why wouldnt jsc call the correct ToString instead without virtual? Console.WriteLine(xx.ToString()); Func<string, Action> y = o => { Console.WriteLine("hello there:"); Console.WriteLine((string)o); //Console.WriteLine("hello there"); //return "done"; return delegate { Console.WriteLine("cannot return long, but can return delegate! " + xx.foo); }; }; // threadpool! var x = y("goo, delegate invoke now works?"); //Console.WriteLine(x); x(); Action a = new MyClass { Field1 = "Field1" }.Invoke; a(); // http://bartoszmilewski.com/2011/10/10/async-tasks-in-c11-not-quite-there-yet/ //var ttt = ThreadPool.QueueUserWorkItem( // new WaitCallback( // delegate // { // Console.WriteLine("at QueueUserWorkItem"); // } // ) //); // X:\jsc.svn\examples\java\hybrid\Test\JVMCLRThreadPool\JVMCLRThreadPool\Program.cs //TaskScheduler.Current. var tt = new Thread( delegate() { Console.WriteLine("can the thread access outer scope?"); Console.WriteLine("!"); Console.WriteLine(xx.foo); // http://stackoverflow.com/questions/13322709/use-of-undeclared-identifier-true // TestFunc.exe.c(1154) : error C2065: 'true' : undeclared identifier var ok = 1; while (ok == 1) { // this keeps going even if the main thread quits? Console.Write("."); Thread.Sleep(100); } } ); tt.Start(); Console.Beep(1200, duration: 1000); tt.Suspend(); Console.Beep(800, duration: 1000); tt.Resume(); Console.Beep(1200, duration: 1000); return 0; }
public void WaitAllWithTimeoutAndSpuriousWake () { /* This is to test that WaitEvent.WaitAll is not going to wait largely * more than its timeout. In this test, it shouldn't wait more than * 1500 milliseconds, with its timeout being 1000ms */ using (ManualResetEvent mre1 = new ManualResetEvent (false)) using (ManualResetEvent mre2 = new ManualResetEvent (false)) using (ManualResetEvent ready = new ManualResetEvent (false)) { var thread = new Thread (() => { ready.Set (); WaitHandle.WaitAll (new [] { mre1, mre2 }, 1000); }); thread.Start (); ready.WaitOne (); Thread.Sleep (10); // wait a bit so we enter WaitHandle.WaitAll ({mre1, mre2}) DateTime end = DateTime.Now.AddMilliseconds (500); while (DateTime.Now < end) { thread.Suspend (); thread.Resume (); } Assert.IsTrue (thread.Join (1000), "#1"); } }
private void mnuItemS_Click(object sender, System.EventArgs e) { try { th = getThread(lVPrio.SelectedItems[0].Text); if(th.ThreadState==System.Threading.ThreadState.Running) { th.Suspend(); } } catch { } finally { loadThreads(); } }
static void Main(string[] args) { string sCmd = ""; Thread tServer = new Thread(new ThreadStart(IperfIO.ServerListen)); tServer.Start(); while (true) { Console.Write("->"); sCmd = Console.ReadLine(); string[] sCmdStr = GlobalVar.StringToFunction(sCmd); switch (sCmdStr[0]) { case "help": GlobalVar.PrintHelp();break; case "h": GlobalVar.PrintHelp(); break; case "?": GlobalVar.PrintHelp(); break; case "d": GlobalVar.debug = true; break; case "p": GlobalVar.PrintLever = 2; break; case "start": if (tServer.ThreadState == ThreadState.Unstarted) { tServer.Start(); } else if (tServer.ThreadState != ThreadState.Running) { tServer.Resume(); } else { Console.WriteLine("Server socket threading state={0}", Convert.ToString(tServer.ThreadState)); } break; case "stop": if (tServer.ThreadState == ThreadState.Running) { tServer.Suspend(); } break; case "server": Console.WriteLine("Server socket threading state={0}", Convert.ToString(tServer.ThreadState)); IperfIO.ServerOMInfo(); break; case "ClientOMInfo": IperfIO.ClientOMInfo(); break; case "ConnectServer": if (GlobalVar.debug) { IperfIO.ConnectServer(sCmdStr[1]); } else { Console.WriteLine("The Debug Mode is {0}!Please set true",Convert.ToString(GlobalVar.debug)); }; break; case "DisConnectServer": if (GlobalVar.debug) { IperfIO.DisConnectServer(sCmdStr[1]); } else { Console.WriteLine("The Debug Mode is {0}!Please set true", Convert.ToString(GlobalVar.debug)); }; break; case "SendMsg": if (GlobalVar.debug) { IperfIO.SendMsg(sCmdStr[1]); } else { Console.WriteLine("The Debug Mode is {0}!Please set true", Convert.ToString(GlobalVar.debug)); }; break; case "c": Console.Clear(); break; default: break;// Console.WriteLine("Input 'h' or '?'"); break; } } }
private void button2_Click(object sender, EventArgs e) { thread.Suspend(); }
public void StackTrace_Thread_Suspended () { Thread t = new Thread (new ThreadStart (EmptyThread)); t.Start (); t.Suspend (); new StackTrace (t, true); }
public static void Main() { mainThread = Thread.CurrentThread; // create the LCD interface var lcd = new SPI_VFDisplay(SPI.SPI_module.SPI1, SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_D10, SPI_VFDisplay.Brightness.VFD_BRIGHTNESS25); // set up the LCD's number of columns and rows: lcd.begin(20, 2, SPI_VFDisplay.Brightness.VFD_BRIGHTNESS25); // set up the LCD's number of columns and rows: lcd.clear(); // create the output helper and attach tot he LCD Display _displayHelper = new OutputHelper(); _displayHelper.DisplayController = lcd; // Print a message to the LCD. _displayHelper.DisplayText("The DIY Brewery|Brew Controller"); Thread.Sleep(5000); _displayHelper.DisplayText("Loading|Settings"); Settings settings = new Settings(); settings.loadSettings(); _displayHelper.HistoryFileName = settings.HistoryFilename; UpdateSettingsMethod.UpdateNetworkConfiguration(settings); _displayHelper.DisplayText("Network|Started"); _displayHelper.DisplayText(UpdateSettingsMethod.GetNetworkIP(settings)); Thread.Sleep(5000); Server WebServer = new Server(80); WebServer.AddResponse(new JSONResponse("temperature", new JSONResponseCheck(GetTemperatureMethod.GetTemperature))); WebServer.AddResponse(new JSONResponse("settings", new JSONResponseCheck(GetSettingsMethod.GetSettings))); WebServer.AddResponse(new JSONResponse("updateSettings", new JSONResponseCheck(UpdateSettingsMethod.UpdateSettings))); WebServer.AddResponse(new JSONResponse("updateMashProfile", new JSONResponseCheck(UpdateMashProfileMethod.UpdateMashProfile))); _displayHelper.DisplayText("Web Server|Started"); Thread.Sleep(5000); NTPTimeService timeService = new NTPTimeService(); timeService.SystemSettings = settings; timeService.Start(); _displayHelper.DisplayText("Internet Time|Service Started"); Thread.Sleep(5000); MashProfileControlService mashProfileService = new MashProfileControlService(_displayHelper); mashProfileService.SystemSettings = settings; mashProfileService.Start(); _displayHelper.DisplayText("Mash Profile|Service Started"); Thread.Sleep(5000); _thermistor = new Thermistor(SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_A0); _thermistor.ResistanceReference = settings.PadResistance; _thermistor.VoltageReference = settings.VoltageReference; TemperatureControlService tempLogger = new TemperatureControlService(_displayHelper, _thermistor, settings); tempLogger.Start(); _displayHelper.DisplayText("Temp Monitor|Started"); Thread.Sleep(5000); PinManagement.engageHeaterButton.OnInterrupt += new NativeEventHandler(EngageHeaterButton_OnInterrupt); PinManagement.setTemperatureUpButton.OnInterrupt += new NativeEventHandler(TemperatureSetUp_OnInterrupt); PinManagement.setTemperatureUpDown.OnInterrupt += new NativeEventHandler(TemperatureSetDown_OnInterrupt); PinManagement.allStopButton.OnInterrupt += new NativeEventHandler(AllStop_OnInterrupt); _displayHelper.DisplayText("Inputs|Active"); mainThread.Suspend(); }
/// <summary> /// Слага алгоритъма на пауза - може да бъде продължен от визуалната среда /// </summary> protected void Pause() { if (AlgorithmSuspended != null) AlgorithmSuspended(); algoThread = Thread.CurrentThread; algoThread.Suspend(); }
/// <summary> /// Handles the touch up event. /// </summary> /// <param name="e">Touch event arguments.</param> /// <returns>Touch event arguments.</returns> public override TouchEventArgs OnTouchUp(TouchEventArgs e) { if (_calibrating) { Settings.CX[_currentCalPoint] = (short)e.Point.X; Settings.CY[_currentCalPoint] = (short)e.Point.Y; if (_currentCalPoint == Settings.Points.Length - 1) { _calibrating = false; _canvas.Clear(); Invalidate(); _text1.FontColor = Colors.Blue; _text1.Visible = true; Thread.Sleep(250); Touch.ActiveTouchPanel.SetCalibration(Settings.Points.Length, Settings.SX, Settings.SY, Settings.CX, Settings.CY); GlideTouch.Calibrated = true; _thread = new Thread(Countdown); _thread.Priority = ThreadPriority.AboveNormal; _thread.Start(); _exitBtn.Visible = true; _startBtn.Visible = true; ModalResult result = ModalResult.Yes;//Glide.MessageBoxManager.Show(String.Empty, "Calibration Complete", ModalButtons.YesNo); try { _thread.Suspend(); _thread = null; } catch { } if (result == ModalResult.Yes) { if (_autoSave) { GlideTouch.SaveCalibration(Settings); _text1.Text = "Calibration set and saved."; } else _text1.Text = "Calibration set but not saved."; Thread.Sleep(1000); TriggerCloseEvent(this); } else { if (GlideTouch.CalSettings != null) { Touch.ActiveTouchPanel.SetCalibration(Settings.Points.Length, Settings.SX, Settings.SY, Settings.CX, Settings.CY); _text1.Text = "Calibration reverted to previous settings."; } else _text1.Text = "Calibration remains set. Cannot revert; previous settings do not exist."; } FillRect(_text1.Rect); _text1.Invalidate(); } else { _currentCalPoint++; DrawCrossHair(Settings.Points[_currentCalPoint].X, Settings.Points[_currentCalPoint].Y); } } return base.OnTouchUp(e); }
public bool Start() { _iepLocal = new IPEndPoint(IPAddress.Any, _localPort); _udpClient = new UdpClient(_localPort); _udpClient.Connect(_rfidIp, _rfidPort); _bConnected = true; SendMsgClearObj(); if(_rfidScanTimer == null) { _rfidScanTimer = new System.Timers.Timer(RfidScanInterval); _rfidScanTimer.Elapsed += RfidScanTimerHandler; _rfidScanTimer.Start(); } else { _rfidScanTimer.Start(); } if(_hRfidRecvThread == null) { ThreadStart threadDelegat = new ThreadStart(recvRfidProc); _hRfidRecvThread = new Thread(threadDelegat); _hRfidRecvThread.IsBackground = true; _hRfidRecvThread.Name = "RFID 接收线程"; _hRfidRecvThread.Start(); _hRfidRecvThread.Suspend(); } else { _hRfidRecvThread.Resume(); } return true; }
private int _instScanInterval = 200; //取指令周期,单位:毫秒 #endregion Fields #region Constructors /// <summary> /// 构造函数 /// </summary> public TansVehicle() { _instExeThread = new Thread(new ThreadStart(InstExeThreadProc)); _instExeThread.Suspend(); //挂起 }
public void TestSuspend () { Thread t = new Thread (new ThreadStart (DoCount)); t.IsBackground = true; t.Start (); CheckIsRunning ("t1", t); t.Suspend (); WaitSuspended ("t2", t); CheckIsNotRunning ("t3", t); t.Resume (); WaitResumed ("t4", t); CheckIsRunning ("t5", t); t.Abort (); TestUtil.WaitForNotAlive (t, "wait13"); CheckIsNotRunning ("t6", t); }
public void Suspend() { _thread.Suspend(); }
private static IEnumerable<StackFrame> GetStackFramesForThread(Thread thread) { #if COREFX throw new NotSupportedException(); #else StackTrace trace; switch (thread.ThreadState) { case System.Threading.ThreadState.Running: thread.Suspend(); trace = new StackTrace(thread, true); thread.Resume(); break; default: trace = new StackTrace(thread, true); break; } return trace.GetFrames(); #endif }
private static IEnumerable<StackFrame> GetStackFramesForThread(Thread thread) { StackTrace trace; switch (thread.ThreadState) { case System.Threading.ThreadState.Running: thread.Suspend(); trace = new StackTrace(thread, true); thread.Resume(); break; default: trace = new StackTrace(thread, true); break; } return trace.GetFrames(); }
/// <summary> /// Конструктор телефонной трубки (ничего лучше в голову не пришло) /// </summary> /// <param name="toip">IP собеседника</param> /// <param name="pr">Порт собеседника</param> public Player(string toip, int pr) { _portReceive = pr; _ToIP = toip; ThreadListen = new Thread(DataReceive); ThreadListen.Start(); ThreadListen.Suspend(); }
public void TestSuspendAbort () { Thread t = new Thread (new ThreadStart (DoCount)); t.IsBackground = true; t.Start (); CheckIsRunning ("t1", t); t.Suspend (); WaitSuspended ("t2", t); CheckIsNotRunning ("t3", t); t.Abort (); int n=0; while (t.IsAlive && n < 200) { Thread.Sleep (10); n++; } Assert ("Timeout while waiting for abort", n < 200); CheckIsNotRunning ("t6", t); }
private void btStartScan_Click(object sender, EventArgs e) { if (btStartScan.Text == "开始扫描") { for (int i = 0; i < lvwVolumes.Items.Count; i++) { if (lvwVolumes.Items[i].Checked == true) { selDriverFlag = 1; break; } } wasteTimer.Enabled = true; btStartScan.Text = "暂 停"; btCleaner.Enabled = true; btCleaner.Text = "取消扫描"; if (search_thread == null) { search_thread = new Thread(new ThreadStart(startsearch)); } if (search_thread.ThreadState == ThreadState.Stopped) { search_thread = null; search_thread = new Thread(new ThreadStart(startsearch)); } if (!search_thread.IsAlive) { search_thread.Start(); } } else { if (btStartScan.Text == "暂 停") { search_thread.Suspend(); wasteTimer.Enabled = false; btStartScan.Text = "继续扫描"; } else { if (btStartScan.Text == "继续扫描") { search_thread.Resume(); wasteTimer.Enabled = true; btStartScan.Text = "暂 停"; } else { if (btStartScan.Text == "重新扫描") { ScanResLisv.Items.Clear(); ScanFileCount = 0; for (int i = 0; i < lvwVolumes.Items.Count; i++) { if (lvwVolumes.Items[i].Checked == true) { selDriverFlag = 1; break; } } wasteTime = 0; wasteTimer.Enabled = true; btStartScan.Text = "暂 停"; btCleaner.Enabled = true; btCleaner.Text = "取消扫描"; if (search_thread == null) { search_thread = new Thread(new ThreadStart(startsearch)); } if (search_thread.ThreadState == ThreadState.Stopped) { search_thread = null; search_thread = new Thread(new ThreadStart(startsearch)); } if (!search_thread.IsAlive) { search_thread.Start(); } } } } } }