Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You don't need to use a lock here at all as the <code>btn_Click</code> method will only be called by the UI thread (unless you explicitly call it from another thread which would be bad).</p> <p>So the code only needs a <code>null</code> check to ensure you only have one worker thread created.</p> <pre><code>public class MainForm : Form { private Thread workerThread = null; public MainForm() { } public void btn_Click() { if (workerThread == null) { var worker = new MyWorker(); worker.StartEvent += (s, e) =&gt; { //Invoke some delegate to interact with the window }; workerThread = new Thread(worker.DoWork); workerThread.Start(); } } } </code></pre> <hr> <p>EDIT: In response to a comment from the OP.</p> <pre><code>public class MainForm : Form { private Thread workerThread = null; public MainForm() { } public void btn_Click() { if (workerThread == null || workerThread.IsAlive == false) { var worker = new MyWorker(); worker.StartEvent += (s, e) =&gt; { //Invoke some delegate to interact with the window }; worker.EndEvent += (s, e) =&gt; { //Clean up }; workerThread = new Thread(worker.DoWork); workerThread.Start(); } } } </code></pre> <p>And <code>MyWorker</code> now looks like this:</p> <pre><code>public class MyWorker { public event EventHandler StartEvent; public event EventHandler EndEvent; public void OnStart() { var se = this.StartEvent; if (se != null) { se(this, new EventArgs()); } } public void OnEnd() { var ee = this.EndEvent; if (ee != null) { ee(this, new EventArgs()); } } public void DoWork() { this.OnStart(); // do some work this.OnEnd(); } } </code></pre>
 

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