C # calling backgroundWorker from a thread other than a UI thread

I am trying to download loadingFormas below. But this does not work, loadForm does not disappear, the event is RunWorkerCompletednot called.

And also I need to call loadingFormand several times backgroundWorker, since I can completely get rid of loadingFormand backgroundWorkerafter each call?

I think there are a lot of errors in my code, but I don’t know how to fix it. Could you show me how to solve my problem and indicate where I need to fix it? Thank you very much in advance.

public partial class loginForm : Form
{
     //....
     private loadingForm lf;
     private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
     {
          lf.Show();
          While (backgroundWorker1.isBusy)
               Application.DoEvents();
     }
     private void backgroundWorker1_RunWorkerCompleted(object sender, DoWorkEventArgs e)
     {
          lf.Close();
     }
     private void connect()
     {
          //....
          Thread mainThread = new Thread(ThreadStart(listentoServer));
          mainThread.Start();
     }
     private void listentoServer()
     {
          //....
          lf = new loadingForm();
          backgroundWorker1.RunWorkerAsync();
          //....
          backgroundWorker1.CancelAsync();
          //.... 
     }
}
+3
source share
3 answers

. , , .

BackgroundWorker (EAP). , . , Thread ( ).

UI . STA, (, Application.DoEvents).

, Thread, ( , STA , ), BGW, .

, - , ?

WinForms AFAIK, . .

+2

, (, , , ), backgroundWorker_DoWork backgroundWorker_RunWorkerCompleted. - ( , backgroundWorker), :

backgroundWorker.DoWork += new EventHandler(backgroundWorker_DoWork);
backgroundWorker.RunWorkerCompleted += new EventHandler(backgroundWorker_RunWorkerCompleted);

, , EventHandler .

+1

, , , , .

+1
source

Source: https://habr.com/ru/post/1781732/


All Articles