-3

嗨,我是第一次在线程上工作,不确定如果我做得正确,我会收到错误消息:

调用线程无法访问此对象,因为不同的线程拥有它”异常

   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;

    }
4

2 回答 2

3

尝试:

private void MigrateProductStats(object corporationIdObj)
{
    Invoke(new Action(() =>
    {
       // after thread completion I need to Enable my buttons.
       buttonProductStatsAndRetailerStats.Enabled = true;
       buttonSummariseProductStats.Enabled = true;
    });
}
于 2013-09-08T18:15:21.000 回答
0

甚至比Control.Invoke用来BackgroundWorker为您处理线程更好。它在 UI 线程上生成进度和完成事件,以简化 UI 更新。

如果您使用的是 C# 5,您还可以使用async启动后台处理并await在处理完成时导致 UI 更新发生。

于 2013-09-08T18:18:33.847 回答