Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, this code is wrong - the outcome is not really defined, but it would be quite reasonable for it to throw an exception at the <code>mrEvent.WaitOne()</code>, since <code>mrEvent</code> is the almost-certainly-now-disposed <code>ManualResetEvent</code>. Technically there's a chance that the worker thread was all ready to go, and the worker thread did its "some processing..." faster than the primary thread did the "some other processing...", but: I wouldn't rely on it. So in most cases: <code>mrEvent</code> is dead already.</p> <p>As for how to avoid this: perhaps this simply isn't a scenario for <code>using</code>. But it occurs that since the worker thread does a <code>WaitOne</code>, the worker thread's <code>WaitOne</code> <strong>cannot</strong> complete before the primary thread performs the <code>mre.Set()</code> call - so you could exploit that and move the <code>using</code> to the worker:</p> <pre><code> var mre = new ManualResetEvent(false); var bgWkr = new BackgroundWorker(); bgWkr.DoWork += delegate(object sender, DoWorkEventArgs e) { using(var mrEvent = e.Argument as ManualResetEvent) { // some processing... mrEvent.WaitOne(); } // broadcast an event }; bgWkr.RunWorkerAsync(mre); // some other processing... // hook into the same event mre.Set(); </code></pre> <p>Note, however, that this raises an interesting question of what happens if the primary thread throws an exception in the "some other processing..." - the call to <code>mre.Set()</code> would never be reached, and the worker thread would never exit. You might want to do the <code>mre.Set()</code> in a <code>finally</code>:</p> <pre><code> var mre = new ManualResetEvent(false); try { var bgWkr = new BackgroundWorker(); bgWkr.DoWork += delegate(object sender, DoWorkEventArgs e) { using(var mrEvent = e.Argument as ManualResetEvent) { // some processing... mrEvent.WaitOne(); } // broadcast an event }; bgWkr.RunWorkerAsync(mre); // some other processing... } finally { // hook into the same event mre.Set(); } </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