Pause and continue implementation, can use Thread.Suspend and Thread.Resume and these two methods, in the VS2010 hint is outdated, not recommended to use, on-line access to some information, found that there is an event notification method is good, the general principle of event notification is that the thread is suspended during execution, wait until other thread notification to continue execution Go on, it really can play a pause and continue the effect. However, this pause is passive, I need to be active pause, that is, click the button, the thread pauses, then click the button, the thread continues to execute.
Finally, I think of a more alternative approach, the general idea is as follows: or the use of event notification, waiting for notification in the thread, until the notification to continue execution, and the main thread (form thread) using a timer System.Windows.Forms.Timer to constantly notify the thread, If the timer interval is set to small enough, there is basically no pause. At this point, the program's pause and continue to implement is very simple, I believe everyone has thought, as long as the control timer by the Stop () and start () can control the thread of the pause and continue.
usingSystem; usingSystem.Windows.Forms; usingSystem.Threading; namespacethread pause and continue implementation { Public Partial classForm1:form {//Timer PrivateSystem.Windows.Forms.Timer TM =NewSystem.Windows.Forms.Timer (); //automatically reset event classes//The main use of its two methods WaitOne () and Set (), the former block the current thread, which notifies the blocking thread to continue to executeAutoResetEvent autoevent =NewAutoResetEvent (false); PublicForm1 () {InitializeComponent (); Progressbar.checkforillegalcrossthreadcalls=false; Tm. Interval=1; Tm. Tick+=NewEventHandler (Tm_tick); } //Timer Events voidTm_tick (Objectsender, EventArgs e) {Autoevent.set ();//notifies the blocked thread to continue execution } //Start Private voidbtnStart_Click (Objectsender, EventArgs e) {TM. Start (); Thread T=NewThread (DoWork); T.start (); } //methods executed in the thread Private voidDoWork () { while(progressBar1.Value <progressbar1.maximum) {progressbar1.performstep (); Autoevent.waitone (); //blocks the current thread, waits for notification to continue execution } } //Pause Private voidBtnsuspend_click (Objectsender, EventArgs e) {TM. Stop (); } //continue to Private voidBtnresume_click (Objectsender, EventArgs e) {TM. Start (); } } }
C# Thread Implementation paused continue (GO)