问题描述
这是我的代码:
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;
}
}
但是我注意到,如果我捕获到异常,在所有txtMonitor.InvokeRequired
发送到UI之前,return
可以采取行动,并且我丢失了一些消息".
but I notice that, if I catch an Exception, return
can act before that all txtMonitor.InvokeRequired
has been sent to the UI, and I lost some "message".
如何避免这种情况?
推荐答案
如果我正确理解了您的要求,则可以使用try/catch块的第三部分-最后
If I understand your requirements correctly, then you can use the third part of the try/catch block - finally
因此您的代码将更改为以下形式:
So your code would change to something of the 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
,并且代码将永远不会执行.
A couple of notes - are you sure you only want to run it if InvokeRequired
is true
? If you are running it from a simple button click, for example, and not from a background thread, then InvokeRequired
will be false
and code will never execute.
如果您想知道是否最终将始终被调用,那么这个特定问题已经被问过很多次了.参见.那有一些有趣的反例.
您可以考虑的另一种选择是简单地throw
您的异常.您可以将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);
}
}
这篇关于如何确保InvokeRequired不会中止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!