How to write safe/correct multi-threaded code in .NET?

前端 未结 5 1367
北恋
北恋 2021-01-30 04:50

Today I had to fix some older VB.NET 1.0 code which is using threads. The problem was with updating UI elements from the worker thread instead of the UI-thread. It took me some

5条回答
  •  一向
    一向 (楼主)
    2021-01-30 05:19

    It seems nobody answered the question how to debug multithreaded programs. This is a real challenge, because if there is a bug,it needs to be investigated in real time, which is nearly impossible with most tools like Visual Studio. The only practical solution is to write traces, although the tracing itself should:

    1. not add any delay
    2. not use any locking
    3. be multithreading safe
    4. trace what happened in the correct sequence.

    This sounds like an impossible task, but it can be easily achieved by writing the trace into memory. In C#, it would look something like this:

    public const int MaxMessages = 0x100;
    string[] messages = new string[MaxMessages];
    int messagesIndex = -1;
    
    public void Trace(string message) {
      int thisIndex = Interlocked.Increment(ref messagesIndex);
      messages[thisIndex] = message;
    }
    

    The method Trace() is multithreading safe, non blocking and can be called from any thread. On my PC, it takes about 2 microseconds to execute, which should be fast enough.

    Add Trace() instructions wherever you think something might go wrong, let the program run, wait until the error happens, stop the trace and then investigate the trace for any errors.

    A more detailed description for this approach which also collects thread and timing information, recycles the buffer and outputs the trace nicely you can find at: CodeProject: Debugging multithreaded code in real time 1

提交回复
热议问题