Search code examples
c#multithreadingwinformsbackgroundworker

How to use thread when button click event in windows form?


I`m making windows application.

In my application, working process is like this.

  1. Write a Target site url in text box and Click Start button.

  2. At first, compare between site url in textBox and real site url if it matched, start analyse site and insert into Database, then, showed that data to Datagridviwe in windows forms.

But the problem is... when site information is big, sometimes windows form is freezing.. but it works well....

So I want to add a progress bar and display it, use thread or backgroundworker?

But I never use thread or like that... I don`t know any idea about it...

Please somebody help me or give some advice....

my code is like that.(simplify)

public partial class Site_Statistics : MetroFramework.Forms.MetroForm

{
    public Site_Statistics()
    {
        InitializeComponent();                        
    }

    private void Migration_Statistics_Load(object sender, EventArgs e)
    {

    }

    private void mtbtnStart_Click(object sender, EventArgs e)
    {            
        insertWebApplicationInfo();

        SelectWebApplicationInfo();
    }

    private void insertWebApplicationInfo()
    {
        //Insert to database works here
    }

    private void SelectWebApplicationInfo()
    {
         //Select from database works here
    }
}

Solution

  • It's difficult to decide for you, how you should approach this problem. If you are using .NET 4.5 you could look into the async and await keywords. Video tutorial:

    https://www.youtube.com/watch?v=MCW_eJA2FeY

    If you are "locked" to .NET 3.5 or simply want to learn about the Backgroundworkerthis is a great opportunity, as it is scenarios like this it was built for. Doing work on a background thread and then update the UI can be a hassle, the advantage of using a Backgroundworker is that the events (ProgressChanged, RunworkerCompleted) are raised on the UI thread, so this is taken care of for you. Finally some general tips if you go for the Backgroundworker:

    • The task you wish to perform is placed in the DoWork event
    • Do not update UI in the DoWork event, this is done in the events raised by the backgroundworker
    • If you want to report progress, remember to set the WorkerReportsProgress property and report progress in the doWork event
    • If you want to be able to cancel a task remember to set the WorkerSupportsCancellation property and handle cancellation in the doWork event

    For more info on the backgroundworker there are many good articles if you do some googling :)

    This msdn page has about all the info on Background Workers you could need including examples.