【问题标题】:Code is getting canceled代码被取消
【发布时间】:2014-01-12 05:43:32
【问题描述】:

我的后台工作人员有问题...它只是停止...它没有通过它应该通过的所有代码...

在下面的代码中,它只是停在String gName = comboBox1.SelectedItem.ToString(); 没有任何错误.. 下面的代码根本没有运行.. 我通过在ZipFile pack = new ZipFile(); 放置一个断点来测试这个...断点没有被触发...我一遍又一遍地检查我的代码...我不知道为什么会这样...

后台工作人员:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
   String appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString();
   String gpsPath = appDataFolder + "/GameProfileSaver";
   String userDir = gpsPath + "/profiles/" + currentUserLabel.Text;

   XmlDocument doc = new XmlDocument();
   doc.Load(userDir + "\\games.xml");
   String gName = comboBox1.SelectedItem.ToString();
   ZipFile pack = new ZipFile();
   foreach (XmlNode node in doc.SelectNodes("//games/game[gameName='" + gName + "']/Files/file"))
   {
      try
      {
         if (!Directory.Exists(userDir + "\\" + gName))
         {
            Directory.CreateDirectory(userDir + "\\" + gName);
         }
         pack.AddFile(node.InnerText);
      }
      catch (Exception ex)
      {
         MessageBox.Show(ex.Message);
      }
   }
   pack.Save(userDir + "\\" + gName);
}

【问题讨论】:

  • 我现在找不到任何具体的参考资料,但 IIRC DoWork 无法访问表单的元素。尝试将 String gName = comboBox1.SelectedItem.ToString(); 放入 try/catch 中,看看会发生什么

标签: c# multithreading backgroundworker


【解决方案1】:

您应该只从 UI 线程访问 UI 元素。如果你想使用从组合框中选择的值,你应该把它传递给后台工作人员。

您可以查看此答案以了解如何操作:Sending Arguments To Background Worker?

【讨论】:

    【解决方案2】:

    您不能从另一个线程访问窗体控件​​。

    请参阅Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on 以获得解决方案。

    【讨论】:

      【解决方案3】:

      我的猜测是在该行之前有一个未处理的异常。从Source,您正在尝试访问 try catch 之外的组合框。

      You must be careful not to manipulate any user-interface objects in your DoWork event handler.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-15
        • 1970-01-01
        • 2013-01-08
        • 1970-01-01
        相关资源
        最近更新 更多