Passing data to Winforms UI using BeginInvoke

I'm a C # newbie and have a class that needs to pass information about rows to a grid in a window form. What's the best way to do this? I have added some code examples for better understanding.

public class GUIController
{   
    private My_Main myWindow;


    public GUIController( My_Main window )
    {
        myWindow = window;
    }

    public void UpdateProducts( List<myProduct> newList )
    {
        object[] row = new object[3];

        foreach (myProduct product in newList)
        {
            row[0] = product.Name;
            row[1] = product.Status;
            row[2] = product.Day;

            //HOW DO I USE BeginInvoke HERE?
       }
    }
}

      

And the form class is below:

public class My_Main : Form
{
    //HOW DO I GO ABOUT USING THIS DELEGATE?
    public delegate void ProductDelegate( string[] row );
    public static My_Main theWindow = null;

    static void Main(  )
    {            
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        theWindow = new My_Main();
        Application.Run(theWindow);

    }

    private void My_Main_Load( object sender, EventArgs e )
    {            

        /// Create GUIController and pass the window object
        gui = new GUIController( this );
     }

    public void PopulateGrid( string[] row )
    {
        ProductsGrid.Rows.Add(row);
        ProductsGrid.Update();

    }
}

      

+2


a source to share


1 answer


Like this:

myWindow.BeginInvoke(new My_Main.ProductDelegate(myWindow.PopulateGrid), new object[] { row });

      

However, you should use Invoke

/ BeginInvoke

if your code is running on a background thread.



If your method UpdateProducts

runs on the UI thread, you don't need to BeginInvoke

; you can simply call this method as usual:

myWindow.PopulateGrid(row);

      

If you call BeginInvoke

, you need to create a separate instance of the array in each iteration, moving the declaration row

inside the loop.

+1


a source







All Articles