How to use multithreading with Winform?

前端 未结 9 1334
无人及你
无人及你 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

    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 ! :)

提交回复
热议问题