There is a code snippet:
Dataflow :

var ActionBlock = TransformBlock<ActionParams, string>(async n => try { Task.Run(n.func); } catch (Exception e) { if (MessageBoxResult.Yes == ExceptionMessageBase(e.Message, a)) { //бла бл } } )}; 

What is sent to him:

 public static void Auth() { Api ap = new Api(); AuthPool.Add(() => { ap.Authorize(_aap); }, new ActionParams()); } 

Add:

  public void Add(Action func, PMData data, string name = null) { ActionParams _pack = new ActionParams(); _pack.TargetAction = func; _pack.ActionName = name; _pack.Data = data; ActionBlock.Post(_pack); } 

But the exception handling arising n.func does not work. More precisely, the exception call inside the function is triggered and the program crashes.

If n.func run without a Task then the exception is caught perfectly. But how to catch exceptions arising in the thread where the function is executed and process it in external code?

    2 answers 2

    You need

     await Task.Run(n.func); 

    This will throw an exception into the try / catch block.

    • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin

    The solution came out like this:

      var ActionBlock = TransformBlock<ActionParams, string>(async n => try { await Task.Run(()=> { try { n.func(); } catch (Exception e) { throw new Exception(e.Message, e.innerException); } }); } catch (Exception e) { if (MessageBoxResult.Yes == ExceptionMessageBase(e.Message, a)) { //бла бл } } )}; 
    • one
      Wait, why should you catch an exception so that you can immediately throw it again? - VladD
    • one
      Why not just await Task.Run(() => n.func()); ? It must be exactly the same. - VladD
    • @VladD, alas for some reason, in my case, 'Task' was swallowed. It seems that I checked everything that I could and there was nothing unusual in the called code. And this decision is just for such cases. Of course it can and bydlovato looks, but quite working. - BwehaaFox
    • Hmm, very strange. Maybe you have an Exception type in another namespace? - VladD
    • @VladD, well, an exception is generated in the used API and it generates its own exception, and it has its own clear namespaces. - BwehaaFox