Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB C# Driver and Thread Safety

In the documentation for MongoClient, MongoServer, MongoDatabase and MongoCollection<T> I see that it's said that they are thread-safe.

Question: Does that mean I can have (for example) static fields of them in a class and access them from any Task/Thread?

Like:

public static MongoClient Client = new MongoClient(Properties.Settings.Default.MongoConnStr);
public static MongoServer Server = Client.GetServer();
public static MongoDatabase DraftDB = Server.GetDatabase("draftdb");
public static MongoCollection<MyDoc> Docs = Program.DraftDB.GetCollection<Location>("mydocs");

Specially about MongoCollection<T>; I want to be sure that something like var cursor = Docs.Find(query).SetLimit(50); does not perform a mutation on the MongoCollection<T> (It's static state to be precise).

like image 259
Kaveh Shahbazian Avatar asked Jun 16 '13 08:06

Kaveh Shahbazian


People also ask

What is MongoDB C driver?

The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages. It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.

Can you use MongoDB with C#?

By developing with C# and MongoDB together one opens up a world of possibilities. Console, window, and web applications are all possible. As are cross-platform mobile applications using the Xamarin framework.


1 Answers

From this page you know that MongoServer, MongoDatabase, MongoClient, MongoCollection and MongoGridFS are thread safe. MongoCursor is specifically not thread-safe.

This means you can safely access them from multiple tasks without worrying about that changing their "state" - however you still have to take care around how to set or change their values.

Specifically to your question, querying a collection (which returns a cursor object) does not mutate the MongoCollection object.

like image 162
Asya Kamsky Avatar answered Sep 17 '22 19:09

Asya Kamsky