Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A "cancel flag" is the way to do it, though not a global one, necessarily. The unavoidable point is that you need <strong>some</strong> way to signal to the thread that it should stop what it's doing.</p> <p>In the case of <code>BeginInvoke</code>, this is hard to do with anything but a global flag, because the work is carried out on the threadpool, and you don't know which thread. You have a couple of options (in order of preference):</p> <ol> <li>Use the <code>BackgroundWorker</code> instead of <code>BeginInvoke</code>. This has <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync.aspx" rel="nofollow noreferrer">cancellation functionality baked-in</a>. This has other benefits, like <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.progresschanged.aspx" rel="nofollow noreferrer">progress monitoring</a>, and <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkercompleted.aspx" rel="nofollow noreferrer">"Work complete" callbacks</a>. It also nicely <a href="https://stackoverflow.com/questions/258662/unhandled-exceptions-in-backgroundworker">handles exceptions</a>.</li> <li>Use <code>ThreadPool.QueueUserWorkItem</code>, passing in an object as the state that has a <code>Cancel()</code> method that sets a <code>Cancelled</code> flag that the executing code can check. Of course you'll need to keep a reference to the state object so you can call <code>Cancel()</code> on it (which is something the <code>BackgroundWorker</code> does for you - you have a component on your form. (Thanks to <a href="https://stackoverflow.com/users/93623/fredrik-mork">Fredrik</a> for reminding about this).</li> <li>Create your own <code>ThreadStart</code> delegate, passing in a state object as with option 2.</li> </ol>
    singulars
    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.
    3. VO
      singulars
      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