这是我的代码:
foreach (var pathCartella in folderList)
{
try
{
// some operation
if (txtMonitor.InvokeRequired)
{
txtMonitor.BeginInvoke(new MethodInvoker(delegate { txtMonitor.AppendText(pathCartella + Environment.NewLine); }));
}
}
catch (Exception err)
{
// some operation
return;
}
}
但我注意到,如果我捕获到异常,return 可以在所有 txtMonitor.InvokeRequired 发送到 UI 之前执行,并且我丢失了一些“消息".
我怎样才能避免这种情况?
请您参考如下方法:
如果我正确理解您的要求,那么您可以使用 try/catch block 的第三部分 - finally
The finally block is useful for cleaning up any resources allocated in the try block. Control is always passed to the finally block regardless of how the try block exits. This statement takes the following form:
因此您的代码将更改为以下形式:
foreach (var pathCartella in folderList)
{
try
{
// some operation
}
catch (Exception err)
{
// some operation
return;
}
finally
{
if (txtMonitor.InvokeRequired)
{
txtMonitor.BeginInvoke(new MethodInvoker(delegate { txtMonitor.AppendText(pathCartella + Environment.NewLine); }));
}
}
}
注意事项 - 您确定仅在 InvokeRequired 为 true 时才运行它吗?例如,如果您通过简单的按钮点击运行它,而不是从后台线程运行,则 InvokeRequired 将为 false,代码将永远不会执行。
如果您想知道 finally 是否总是会被调用,那么这个问题已经被问过很多次了。参见 If I return out of a try/finally block in C# does the code in the finally always run?例如。这有一些有趣的反例。
您可以考虑的另一个选择是简单地抛出您的异常。您可以将 pathCartella 作为错误消息的一部分传递,这样您就知道异常发生在什么路径上,以及异常是什么。然后你的调用者可以处理这个。例如:
foreach (var pathCartella in folderList)
{
try
{
// some operation
}
catch (Exception err)
{
// some operation
//The original exception becomes the inner exception (so you can get original
//error and stack trace etc). The new exception message contains the path.
throw new Exception(
String.Format("Failed to perform operation on '{0}'", pathCartella),
err);
}
}
