c# - How can I ensure that InvokeRequired will not aborted? -
this code:
foreach (var pathcartella in folderlist) { try { // operation if (txtmonitor.invokerequired) { txtmonitor.begininvoke(new methodinvoker(delegate { txtmonitor.appendtext(pathcartella + environment.newline); })); } } catch (exception err) { // operation return; } } but notice that, if catch exception, return can act before txtmonitor.invokerequired has been sent ui, , lost "message".
how can avoid this?
if understand requirements correctly, can use third part of try/catch block - finally
the block useful cleaning resources allocated in try block. control passed block regardless of how try block exits. statement takes following form:
so code change of form:
foreach (var pathcartella in folderlist) { try { // operation } catch (exception err) { // operation return; } { if (txtmonitor.invokerequired) { txtmonitor.begininvoke(new methodinvoker(delegate { txtmonitor.appendtext(pathcartella + environment.newline); })); } } } a couple of notes - sure want run if invokerequired true? if running simple button click, example, , not background thread, invokerequired false , code never execute.
if wondering whether called, particular question has been asked many times. see if return out of try/finally block in c# code in run? example. has interesting counter-examples.
the other option consider throw exception. pass pathcartella part of error message, know path exception happened on, , exception was. caller can handle this. example:
foreach (var pathcartella in folderlist) { try { // operation } catch (exception err) { // operation //the original exception becomes inner exception (so can original //error , stack trace etc). new exception message contains path. throw new exception( string.format("failed perform operation on '{0}'", pathcartella), err); } }
Comments
Post a Comment