Multi-threading towing

I have an application that handles an event callback, in my case this is a DataReceived event in SerialPort. In this callback, I have business logic that should have an exception raised in another thread. This thread waits for the event listener to send it a message or to report that an exception has occurred.

What is the best way to keep stack trace in threads?

Simply transferring the thread to the workflow and rebuilding it will lose stack trace.

+4
source share
7 answers
  • Depending on your approach, for example, TPL: throw -> AggregateException.
  • BackGroundWorker → .
  • → .
  • → throw → .
  • Async/await → throw AggregateException ( ).

, .

Async/ .

BackGroundWroker - , - .

( ), ; .

AggregateException. , . ( )

+2

.NET 4.5, ExceptionDispatchInfo :

Exception exception = ...;
ExceptionDispatchInfo.Capture(exception).Throw();

.NET 4.0, :

Exception exception = ...;
typeof(Exception).InvokeMember("PrepForRemoting",
    BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
    null, exception, new object[0]);
throw exception;
+2

:

-, ( ) , .

, , ( ). , . , ( , ). : , .

0

, ,
That thread is waiting for the event listener to send it a message, or let it know an exception has occurred.

, , , Exception .

0

" " - , , InnerException:

// retain the exception type, but don't lose the stack trace.
Exception instance = (Exception)Activator.CreateInstance(ex.GetType(), "", ex);
throw instance;

, .

0
0

, :

public class MyProcessor
{
    List<Exception> _threadExceptions = new List<Exception>();

    public void Enqueue(SomeJob job)
    {
        if (_threadExceptions.Count > 0)
        {
            var myList = _threadExceptions; 
            _threadExceptions = new List<Exception>();
            throw new AggregateException(myList);
        }

        //do some work
    }

    private static void YourThreadFunc()
    {
        try
        {
            //listen to the port
        }
        catch (Exception ex)
        {
            _threadExceptions.Add(ex);
        }
    }
}

Enqueue, , , - ( ).

0

Source: https://habr.com/ru/post/1538067/


All Articles