-3

Hi I am first time working on Threads not sure If I am doing correct I am getting Error saying :

The calling thread cannot access this object because a different thread owns it" exception

   private void ImportProductStatsButtonClick(object sender, EventArgs e)
    {
        // Get the currently selected manufacturer from the combo box
        var selected = comboBoxCorporation.SelectedItem;
        buttonProductStatsAndRetailerStats.Enabled = false;
        buttonSummariseRetailerStats.Enabled = false;
        buttonSummariseProductStats.Enabled = false;
       // Do we have one?
        if (selected != null)
        {
            // Extract the combo record
            var corporation = (ComboBoxCorporrationItem)selected;

            // Do we have one?
            if (corporation.Corporation != null)
            {
                // yes
                // Make this on a seperate thread so that the UI continues to work
                var thread = new Thread(MigrateProductStats);
              thread.Start(corporation.Corporation.Id); // This enables me to pick the manufacturer that we are summarizing for
             }
        }

    }

 private void MigrateProductStats(object corporationIdObj)
    {
       // after thread completion I need to Enable my buttons.
        buttonProductStatsAndRetailerStats.Enabled = true;
        buttonSummariseProductStats.Enabled = true;

    }
62071072SP
  • 1,963
  • 2
  • 19
  • 38

2 Answers2

3

Try with:

private void MigrateProductStats(object corporationIdObj)
{
    Invoke(new Action(() =>
    {
       // after thread completion I need to Enable my buttons.
       buttonProductStatsAndRetailerStats.Enabled = true;
       buttonSummariseProductStats.Enabled = true;
    });
}
Alessandro D'Andria
  • 8,663
  • 2
  • 36
  • 32
0

Even better than Control.Invoke would be to use BackgroundWorker to handle threading for you. It generates progress and completion events back on the UI thread to make UI updates easy.

If you're using C# 5, you can also use async to start the background processing and await to cause the UI updates to occur when processing completes.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720