C# driver susceptible to thread-starvation deadlocks

XMLWordPrintableJSON

    • Type: Bug
    • Resolution: Done
    • Priority: Minor - P4
    • None
    • Affects Version/s: 2.0.1
    • Component/s: None
    • None
    • Environment:
      Windows
    • None
    • None
    • None
    • None
    • None
    • None
    • None

      Calling IMongoCollection<T>.InsertOneAsync from a thread of the .NET ThreadPool can lead to deadlock by thread-starvation (here is a link describing this phenomenon, see topic 'deadlock' on the page).

      I suppose that the internal implementation of the C# driver relies on the .NET ThreadPool, either directly or indirectly through calls to the networking API of the .NET framework.

      It could be argued that it is 'by design' and that the bug is in my code, which should not run in a thread from the .NET ThreadPool to begin with.

      My answer would be that I should not have to make assumptions about the way the driver is implemented, therefore this is a case of a leaky abstraction. Furthermore, if this limitation is 'by design', the possibility of thread-starvation deadlock should be properly documented.

      Here is an example of a program that exhibits the issue:

      static void Main(string[] args)
      {
          var client = new MongoClient("mongodb://localhost:27017");
          var database = client.GetDatabase("ThreadStarvationDeadlock");
          var collection = database.GetCollection<BsonDocument>("Foo");
      
          var tasks = new Task[500];
      
          for (int i = 0; i < tasks.Length; ++i)
          {
              tasks[i] = Task.Run(() =>
              {
                  var document = new BsonDocument { { "Bar", 0 } };
                  collection.InsertOneAsync(document).Wait();
              });
          }
      
          Console.WriteLine("Waiting...");
          Task.WaitAll(tasks);
      
          Console.WriteLine("Done. <Enter> to quit.");
          Console.ReadLine();
      }
      

            Assignee:
            Robert Stam
            Reporter:
            ZunTzu
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: