Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should never use suspend/resume, be it in Java or C#, because only your threads know when it's safe to stop or suspend.</p> <p>Instead use <strong>synchronization primitives</strong> like <strong>events</strong> to control the execution of a thread.</p> <p>Here is a little sample using <strong>WinForms</strong> (so you just need to add a reference to <strong>System.Windows.Forms</strong>):</p> <pre><code>using System.Threading; using System.Windows.Forms; using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Label label = new Label { Dock = DockStyle.Top }; Button button = new Button { Text = "||", Dock = DockStyle.Bottom }; Form form = new Form(); form.Controls.Add(label); form.Controls.Add(button); bool @continue = true; bool isRunning = true; ManualResetEvent run = new ManualResetEvent(true); int i = 0; form.Load += (s, a) =&gt; { ThreadPool.QueueUserWorkItem(o =&gt; { while (@continue) { run.WaitOne(); label.Invoke((Action)(() =&gt; { label.Text = i++.ToString(); })); Thread.Sleep(1000); } }); }; button.Click += (s, a) =&gt; { isRunning = !isRunning; if (isRunning) run.Set(); else run.Reset(); button.Text = isRunning ? "||" : "&gt;&gt;"; }; form.Disposed += (s, a) =&gt; @continue = false; Application.Run(form); } } } </code></pre> <p>So the thread that counts (note that this is not accurate at all if you want to count seconds) checks each time if it must continue or wait using "<strong>WaitOne</strong>".</p> <p>The UI thread controls this by activating/deactivating the <strong>event</strong>: when you click on the button the event state is toggled.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload