How to use multithreading with Winform?

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

    You can only set progress bar user control properties from the UI thread (the WinForm one). The easiest way to do it with your BackgroundWorker is to use the ProgressChanged event:

    private BackgroundWorker bwForm;
    private ProgressBar progressBar;
    

    In WinForm constructor:

    this.progressBar = new ProgressBar();
    this.progressBar.Maximum = 100;
    this.bwForm = new BackgroundWorker();
    this.bwForm.DoWork += new DoWorkEventHandler(this.BwForm_DoWork);
    this.bwForm.ProgressChanged += new ProgressChangedEventHandler(this.BwForm_ProgressChanged);
    this.bwForm.RunWorkerAsync();
    

    ...

    void BwForm_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker bgw = sender as BackgroundWorker;
        // Your DoConvert code here
        // ...          
        int percent = 0;
        bgw.ReportProgress(percent);
        // ...
    }
    
    void BwForm_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        this.progressBar.Value = e.ProgressPercentage;
    }
    

    see here: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

    EDIT

    So I didn't understand your question, I thought it was about showing progress bar progression during work. If it's about result of work use e.Result in the BwForm_DoWork event. Add a new event handler for completed event and manage result:

    this.bwForm.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.BwForm_RunWorkerCompleted);
    

    ...

    private void BwForm_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        YourResultStruct result = e.Result as YourResultStruct;
        if (e.Error != null && result != null)
        {
            // Handle result here
        }
    }
    

提交回复
热议问题