c# - Async-Await, exception handling and continuation using TaskContinuationOptions.OnlyOnFaulted -


I have the following code for the sample console application, but using TaskContinuationOptions.OnlyOnFaulted never calls.

  using the system; Using System.Threading; System usage threading. Task; Namespace sample {class program {public static zero main (string [] args) {int index = 0; Var CTS = new cancellation TokenSaur (); Task.Factory.StartNew ((=) NewTask (index), cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default) .continueWith (HandleException, cts.Token, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); // some code // ... console Readline (); } Private static async Tasks Newtask {int Index} {Console.WriteLine (index); Wait () wait; } Private Static Async Task Wait () {Waiting for the job Diley (500); Throw a new exception ("123 test"); } Private Static Zero Handle Expansion {If (work! = Null & work exception! = Null} {var exceptions = task.Exception.Flatten () .InnerXpress; if exception (exception! = Null) foreach (Exceptions in exceptions) Console WriteLine (Exception Message);}}}}  

Here, when an exception wait () method, Handle Exception (...) is being called instead, either program crash or debugger shows by an unrestricted exception dialog box.

edit: NewTask method return type .

By calling factory.startNew , you are actually creating a method whose method initiates your actual work , But it does not have to continuously run on your actual work; Only external, unnecessary work (which will not throw an exception) is one.

Additionally, your async function async zero This consistency makes it impossible to add I'm going a step further and say that you should never, ever do the function that is async null . It should always be async task .

If you make that syntax change, your calling syntax is really simple:

  Nutsk (index). Continue (handle exception, CTS.Token, Task Continuation Options. Only On Faulted, Task Scheduler Default);  

However, keep in mind that cancellation is not something you get for free; You either are required to have your tokens passed with other asynchronous tasks to use it or you need to check it yourself (or phone .hrowIfCancellationRequested () ).

As a separate, any work from the conference that works work or work < T & gt; Ends its name with async (i.e. its name should be newtasync ).


Comments

Popular posts from this blog

import - Python ImportError: No module named wmi -

Editing Python Class in Shell and SQLAlchemy -

lua - HowTo create a fuel bar -