gpt4 book ai didi

c# - BackgroundWorker 调用目标抛出的异常

转载 作者:行者123 更新时间:2023-11-30 20:59:07 24 4
gpt4 key购买 nike

我有以下代码:

public void extractZipFile()
{
if (!System.IO.Directory.Exists(extractDirectory))
System.IO.Directory.CreateDirectory(extractDirectory);

BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.ProgressChanged += (o, e) =>
{
progbarExtract.Value = Convert.ToInt32(e.ProgressPercentage);
};

lblExtracting.Text = "Extracting...";
worker.DoWork += (o, e) =>
{
using (ZipFile zip = ZipFile.Read(zipFile))
{
int step = Convert.ToInt32(zip.Count / 100.0);
int percentComplete = 0;
foreach (ZipEntry file in zip)
{
file.Extract(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\XBMC Library Importer\\XBMC_Files", ExtractExistingFileAction.OverwriteSilently);
percentComplete += step; //When I comment this out I don't get an exception
worker.ReportProgress(percentComplete);
}
}
};

worker.RunWorkerAsync();
}

我不明白为什么语句 percentComplete += step; 会导致错误(Exception has been thrown by the target of an invocation.)。

我该如何解决这个问题?

另外,有人知道提取完成后如何显示消息框 (MessageBox.Show()) 吗?

如有任何帮助,我们将不胜感激。

最佳答案

您需要查看异常的 InnerException 属性以了解 TargetInvocationException 的原因。

粗略猜测一下:您错误地计算了 step 的值。它应该是 100.0/zip.Count。应该也是双标的。因此,当 .zip 文件包含超过 100 个文件时,您将冒着将进度增加到 100 以上的风险。当您将该值分配给 ProgressBar.Value 时,这将会爆炸。您应该已经注意到进度条在小文件上也表现不正常,根本不会增加。

调试像这样难以捉摸的错误的一个好方法是调试 + 异常,勾选 CLR 异常的抛出复选框。调试器现在将在抛出异常时停止。

关于c# - BackgroundWorker 调用目标抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15605961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com