4

例外是在代码上:

private void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
   ActiveDownloadJob adJob = e.UserState as ActiveDownloadJob;
   if (adJob != null && adJob.ProgressBar != null)
   {
      adJob.ProgressBar.Invoke((Action)(() => adJob.ProgressBar.Value = e.ProgressPercentage));
   }
}

在线上:

adJob.ProgressBar.Invoke((Action)(() => adJob.ProgressBar.Value = e.ProgressPercentage));

这是 form1 中的 ActiveDownloadJob 类:

class ActiveDownloadJob
{
            public DownloadImages.DownloadData DownloadData;
            public ProgressBar ProgressBar;
            public WebClient WebClient;

            public ActiveDownloadJob(DownloadImages.DownloadData downloadData, ProgressBar progressBar, WebClient webClient)
            {
                try
                {
                    this.DownloadData = downloadData;
                    this.ProgressBar = progressBar;
                    this.WebClient = webClient;
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.ToString());
                }
            }
        }

我不确定我是否需要调用此行,因为我现在不使用 backgroundworker ,但我不确定。

这是完整的异常消息:在创建窗口句柄之前,无法在控件上调用 Invoke 或 BeginInvoke

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
       at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
       at System.Windows.Forms.Control.Invoke(Delegate method)
       at WeatherMaps.Form1.DownloadProgressCallback(Object sender, DownloadProgressChangedEventArgs e) in d:\C-Sharp\WeatherMaps\WeatherMaps\WeatherMaps\Form1.cs:line 290
       at System.Net.WebClient.OnDownloadProgressChanged(DownloadProgressChangedEventArgs e)
       at System.Net.WebClient.ReportDownloadProgressChanged(Object arg)
  InnerException: 

我如何在不使用 Invoke 的情况下更改此行,或者如果需要 Invoke,我该如何修复该行和异常?

我知道我应该在 Form1 Form 关闭事件中处理它,但是如何处理呢?我应该在 form1 表单关闭事件中做什么?

4

3 回答 3

5

是的,您得到一个例外,因为Invoke需要将“消息”发布到“消息循环”但Handle尚未创建。

用于InvokeRequired查看是否需要一个Invoke,当 Handle 尚未创建时这将返回 false 所以直接调用它。

var method = (Action)(() => adJob.ProgressBar.Value = e.ProgressPercentage);
if(adJob.ProgressBar.InvokeRequired)
    adJob.ProgressBar.Invoke(method);
else
    method();
于 2013-11-13T15:58:33.430 回答
3

问题是您试图在进度条具有窗口句柄之前对其进行修改。解决它的一种方法是:

if (adJob.ProgressBar.Handle != IntPtr.Zero)
{
    adJob.ProgressBar.Invoke((Action)(() =>
        adJob.ProgressBar.Value = e.ProgressPercentage));
}

这可能是由于您在Form实际显示之前调用此方法所致。

于 2013-11-13T15:54:19.460 回答
-1

尝试一下:

MethodInvoker mi = () => adJob.ProgressBar.Value = e.ProgressPercentage;
if(InvokeRequired) BeginInvoke(mi);
else mi();
于 2013-11-13T15:49:14.343 回答