How to use multithreading with Winform?

前端 未结 9 1306
无人及你
无人及你 2020-12-17 16:27

I\'m a newbie with multithreading. I have a winform that have a label and a progress bar.

I wanna show the processing result. Firstly, I use Application.DoEven

相关标签:
9条回答
  • 2020-12-17 16:55

    Invoke the UI thread. For example:

    void SetControlText(Control control, string text)
    {
        if (control.InvokeRequired)
            control.Invoke(SetControlText(control, text));
        else
            control.Text = text;
    }
    
    0 讨论(0)
  • 2020-12-17 16:55

    Do like this, create a new thread

             Thread loginThread = new Thread(new ThreadStart(DoWork));
    
             loginThread.Start();
    

    Inside the ThreadStart(), pass the method you want to execute. If inside this method you want to change somes controls properties then create a delegate and point it to a method inside which you will be writing the controls changed properties,

             public delegate void DoWorkDelegate(ChangeControlsProperties);         
    

    and invoke the controls properties do like this, declare a method and inside it define the controls new porperties

             public void UpdateForm()
             {
                 // change controls properties over here
             }
    

    then point a delegate to the method, in this way,

             InvokeUIControlDelegate invokeDelegate = new InvokeUIControlDelegate(UpdateForm);
    

    then when you want to change the properties at any place just call this,

             this.Invoke(invokeDelegate);
    

    Hope this code snippet helps you ! :)

    0 讨论(0)
  • 2020-12-17 16:57

    Cleanest way is using BackGroundWorker as you did.

    you just missed some points:

    1. you cannot access your form elements in DoWork event handler because that makes a cross thread method invokation, this should be done in ProgressChanged event handler.
    2. by default a BackGroundWorker will not allow to report progress, as well as in won't allow Cancelling the operation. When you add a BackGroundWorker to your code, you have to set the WorkerReportsProgress property of that BackGroundWorker to true if you want to call the ReportProgress method of your BackGroundWorker.
    3. In case you need to allow the user to cancel the operation as well, set WorkerSupportsCancellation to true and in your loop in the DoWork event handler check the property named CancellationPending in your BackGroundWorker

    I hope I helped

    0 讨论(0)
提交回复
热议问题