views:

76

answers:

1

Scenario:

I have a windows form that holds a DataGridWiew with 3 pre-defined columns. I have 3 variables declared outside the function and assigned to inside the function. I have a function that enumerates stuff and puts it in the 3 columns, line by line:

string VARIABLE1;
string VARIABLE2;
string VARIABLE3;

private void FunctionEnumerateStuff()
{
    foreach (StuffObject STUFF in StuffCollection)
    {
       VARIABLE1 = STUFF.SubStuff1.ToString();
       VARIABLE2 = STUFF.SubStuff2.ToString();
       VARIABLE3 = STUFF.SubStuff3.ToString();
       DatagridWiew1.Rows.Add(VALUE1, VALUE2, VALUE3); 
    }
}

What I want to do, is to execute this function from a BackGroundWorker process, so that the GUI of the application will be smooth and responsive. I have read up on backgroundworkers but I am having trouble relating, because all examples seems to be of entirely different scenarios and most of them are overwhelmingly complex.

Can some helpful pedagogic soul help me and others with a very basic example of how to get this to work in the simplest way possible. Thanks.

+1  A: 

Here is an example:

class Form1 : Form
{
    private BackgroundWorker Worker { get; set; }

    public Form1()
    {
        Worker = new BackgroundWorker();
        Worker.WorkerSupportsCancellation = true;
        Worker.DoWork += OnWorkerDoWork;
        Worker.RunWorkerCompleted += OnWorkerRunWorkerCompleted;

        // at some point start the worker.
        Worker.RunWorkerAsync();
    }

    void OnWorkerDoWork(object sender, RunWorkerCompletedEventArgs e)
    {
        foreach(var data in someData)
        {
            // if cancelled
            if (e.Cancelled)
                return;

            AddDataToColumn(someData.Var1, someData, Var2, someData.Var3);
        }
    }

    void OnWorkerRunWorkerCompleted(object sender, DoWorkEventArgs e)
    {

    }

    private delegate void AddDataToColumnDelegate(string var1, string var2, string var3);
    private void AddDataToColumn(string var1, string var2, string var3)
    {
        // check if cross-thread operation
        if (InvokeRequired)
        {
            Invoke(new AddDataToColumnDelegate(AddDataToColumn), var1, var2, var3);
            return;
        }

        // Add data to column
        dataGridView1.Rows.Add(var1, var2, var3);
    }
}
Michael