【问题标题】:Winforms PictureBox.Load / LoadAsync don't workWinforms PictureBox.Load / LoadAsync 不起作用
【发布时间】:2015-05-01 10:04:15
【问题描述】:

我有一个包含很多产品的 xml 文件(10,000 种产品到 200,000 种产品甚至更多),我正在尝试编写一个简单的 winform 来获取此 xml 文件并显示产品图像和数据: 这是和 xml 示例:

<catalog>
     <product>
          <name>...</name>
          <price>...</price>
          <description>...</description>
         <imageurl>http://www.boscovs.com/wcsstore/boscovs/images/store/product/thumbnails/60314665830t.jpg</imageurl>
     <product>
     <product>
      ...
     <product>
</catalog>

我正在为这项任务使用背景工作者,所以我的代码如下所示:

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
     XmlNodeList xnList = doc.SelectNodes(...);
     foreach (XmlNode product in xnList)
     {
          PictureBox img = new PictureBox();
          img.Dock = System.Windows.Forms.DockStyle.Fill;
          img.Location = new System.Drawing.Point(3, 28);
          img.Size = new System.Drawing.Size(194, 94);
          img.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;

          //img.LoadAsync(product[...].InnerText);

          img.Load(product[...].InnerText);

          this.Invoke(new MethodInvoker(delegate
          {
              // Execute the following code on the GUI thread.
              this.Controls.Add(img);
          }));
     }
 }

当我使用 img.LoadAsync 时,我看不到任何图像,当我从 8700 中获得图像编号 1990 时,我遇到了这个异常:

An exception of type 'System.ComponentModel.Win32Exception' occurred in 
System.Windows.Forms.dll but was not handled in user code

Additional information: Error creating window handle.

当我使用img.Load 时,有时会得到图像,有时会出现超时异常...

这不是一项艰巨的任务,但是,我怎样才能有一个可以工作的简单代码?

【问题讨论】:

    标签: c# winforms picturebox


    【解决方案1】:

    恐怕这里的问题是您正在对在 UI 线程上运行的 Load 进行跨线程调用。为避免异常,您需要调用调用方法,该方法会将工作分派给 UI 线程:

    img.Invoke(() => { img.Load(...) });
    

    【讨论】:

    • 我这样做是这样的: this.Invoke(new MethodInvoker(delegate { tblLoading.Visible = false; // 在GUI线程上执行以下代码。this.Controls.Add(tblProduct) ; }));
    • 您是否也尝试在img.Load 方法上调用使用Invoke 方法?
    • 不,因为我正在后台工作人员中创建 PictureBox。
    • 我遇到了这个异常:Invoke or BeginInvoke cannot be called on a control until the window handle has been created。但是,我仍然在后台工作人员中创建 PictureBox ......所以那里没有问题。不是吗?
    • " 我正在后台工作人员中创建 PictureBox..." 嗯,这大概是你的问题。您应该只在 UI 线程上创建 WinForms 控件和表单。
    猜你喜欢
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 2011-06-21
    • 2013-03-25
    • 1970-01-01
    相关资源
    最近更新 更多