Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As Martin James mentioned, instead of <strong>polling flags</strong>, you should be using <strong>thread synchronization</strong> mechanisms.</p> <p>This simple example shows how you can do this using <code>Monitor.Wait</code>, <code>Monitor.Pulse</code> and <code>lock</code>.</p> <p>The important difference between this and your code is that this will <strong>stop the thread from running</strong> until the condition has been met, thus <strong>improving</strong> the <strong>performance</strong> of your code.</p> <pre><code>class Program { static void Main(string[] args) { ThreadExample example = new ThreadExample(); Thread thread = new Thread(example.Run); Console.WriteLine("Main: Starting thread..."); thread.Start(); Console.WriteLine("Press a key to send a pulse"); Console.ReadKey(); lock (example) //locks the object we are using for synchronization { Console.WriteLine("Sending pulse..."); Monitor.Pulse(example); //Sends a pulse to the thread Console.WriteLine("Pulse sent."); } thread.Join(); Console.ReadKey(); } } class ThreadExample { public void Run() { Console.WriteLine("Thread: Thread has started"); lock (this) //locks the object we are using for synchronization { Monitor.Wait(this); //Waits for one pulse - thread stops running until a pulse has been sent Console.WriteLine("Thread: Condition has been met"); } } } </code></pre> <p>To modify your code to use this mechanism, you need to maintain the reference to the object you used to start the thread (in this example, I will call it <code>threadObject</code>)</p> <pre><code>private void timer1_Tick_1(object sender, EventArgs e) { TimeSpan remainingTime = endTime - DateTime.UtcNow; if (remainingTime &lt;= TimeSpan.Zero) { label1.Text = "Done!"; timer1.Enabled = false; lock(threadObject){ Monitor.Pulse(threadObject); //You signal the thread, indicating that the condition has been met } } else { //... } } </code></pre> <p>Then, in your <code>test()</code> method, you only need this:</p> <pre><code>private void test() { lock(this) { Monitor.Wait(this); //Will stop the thread until a pulse has been recieved. Invoke(new setLabelMethod(setLabelValue), "yeah"); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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