Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First of all, the problem to avoid "cross-thread operation was not valid" is use <a href="http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx" rel="nofollow">Invoke</a> on controls. You cannot use a control from a different thread.</p> <p>About the second issue, I would implement it in the following way. This is a minimum background worker implementation with cancel support.</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); // Set the background worker to allow the user to stop the process. backgroundWorkerStopCheck.WorkerSupportsCancellation = true; backgroundWorkerStopCheck.DoWork += new DoWorkEventHandler(backgroundWorkerStopCheck_DoWork); } private void backgroundWorkerStopCheck_DoWork(object sender, DoWorkEventArgs e) { try { for (int i = 0; i &lt; 50; i++) { if (backgroundWorkerStopCheck.CancellationPending) { // user cancel request e.Cancel = true; return; } System.Threading.Thread.Sleep(100); } } finally { InvokeEnableStartButton(); } } private void buttonStart_Click(object sender, EventArgs e) { //disable start button before launch work buttonStart.Enabled = false; // start worker backgroundWorkerStopCheck.RunWorkerAsync(); } private void buttonStop_Click(object sender, EventArgs e) { // Tell the backgroundWorker to stop process. backgroundWorkerStopCheck.CancelAsync(); } private void InvokeEnableStartButton() { // this method is called from a thread, // we need to Invoke to avoid "cross thread exception" if (this.InvokeRequired) { this.Invoke(new EnableStartButtonDelegate(EnableStartButton)); } else { EnableStartButton(); } } private void EnableStartButton() { buttonStart.Enabled = true; } } internal delegate void EnableStartButtonDelegate(); } </code></pre> <p>About passing arguments to the worker, you can pass any object in the <code>RunWorkerAsync()</code> method, and its reveived in the <code>backgroundWorkerStopCheck_DoWork</code> method:</p> <pre><code> ... backgroundWorkerStopCheck.RunWorkerAsync("hello"); ... private void backgroundWorkerStopCheck_DoWork(object sender, DoWorkEventArgs e) { string argument = e.Argument as string; // argument value is "hello" ... } </code></pre> <p>Hope it helps.</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