I have a GUI application in which I want to run something in a task, so it will not contain a user interface. I want the unhandled exception in the task to be passed to the application-level exception handler. But:
I was thinking about using dispatcher.invoke, what do you think?
public MainWindow() { InitializeComponent(); MyMethodAsync(); InitializeA(); IntiializeB(); } private void MyMethodAsync() { Task t = Task.Run(() => { //Do some stuff throw new Exception("Throwing some unexpected exception"); }).ContinueWith(MyContinueWith); } private void MyContinueWith(Task task) { if (task.IsFaulted && task.Exception != null) { dispatcher.BeginInvoke(new Action(() => { throw task.Exception; }), null); } }
, . -, TaskScheduler.UnobservedTaskException , :
TaskScheduler.UnobservedTaskException
private void MyMethodAsync() { // Note you should probably register only once, so this may not fit here. TaskScheduler.UnobservedTaskException += (s, e) => GlobalLogger.Log(e); Task t = Task.Run(() => { // Do some staff }).ContinueWith(MyContinueWith); }
, - , - try-catch:
try-catch
private async Task MyMethodAsync() { try { await Task.Run(() => { // Do some staff }); InvokeContinuation(); } catch (Exception e) { // Log. } }
, , Task.Run, , , . , , . , I/O, .
, , ContinueWith , async. , , async/await . , , , , , .
Source: https://habr.com/ru/post/1611758/More articles:Equivalent to SAS Array in R - arraysHow can I describe a table in a cassandra database? - cqlDataTemplate cannot resolve DataType prefix data - c #SQL Choice of two tables with internal join and limit - sqlInstall-Package: Cannot find package 'CommonServiceLocator.MefAdapter - c #PHPUnit 0% coverage with Jetbrains PHPStorm - phpUsing Task.Factory.StartNew with an action that takes a single int parameter - c #ListBox mulitple Selection selects all selected values โโ- c #Is it possible to place the physical body in only one part of the sprite? - iosWhat is the purpose of double underscoring after a single underscore as a parameter to a function / class method? - dartAll Articles