How can I ensure that InvokeRequired will not aborted?

帅比萌擦擦* 提交于 2019-12-24 13:44:10

问题


This is my code:

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;
    }
}

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".

How can I avoid this?


回答1:


If I understand your requirements correctly, then you can use the third part of the 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:

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); }));
        }
    }
}

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.

If you are wondering about whether finally will always be called, then this particular question has been asked many times. See If I return out of a try/finally block in C# does the code in the finally always run? for example. That has some interesting counter-examples.

The other option you could consider is to simply throw your exception. You could pass pathCartella as part of the error message, so you know what path the exception happened on, and what the exception was. Your caller can then handle this. For example:

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);

    }

}


来源:https://stackoverflow.com/questions/16099192/how-can-i-ensure-that-invokerequired-will-not-aborted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!