I have a class that I want to use only in one thread. If I create an object of the class in one thread and use it in another, it will cause lots of problems. Currently, I resolve this problem like this: I have Context class and I want to use it only in one thread:
public class Context
{
public Thread CreatedThread { get; }
public Context()
{
CreatedThread = Thread.CurrentThread;
}
public void AssertThread()
{
if (CreatedThread != Thread.CurrentThread)
{
throw new InvalidOperationException("Use only one thread!");
}
}
//Lot of properties and methods here
}
And here is the usage of Context class in Student class:
public class Student
{
Context context;
public Context Context
{
get
{
if (context == null)
context = new Context();
context.AssertThread();
return context;
}
}
}
And when I use context in a different thread, it will throw an error:
var student = new Student();
var context = student.Context;
Task.Run(() =>
{
var context = student.Context;//InvalidOperationException
});
But this solution is not reliable. For example, when I have another class that uses context, I need to do AssertThread on getting context property. Or when I get the context in a new variable and use it in a different thread, my exception will not be thrown. So, is there any solution to enforce class being used only in one thread?
CodePudding user response:
AFAIK neither the C# language nor the standard .NET APIs provide a way to embed automatically the AssertThread()
check in the start of every public method and property of a class. If you don't like the idea of adding this check manually, and you are serious about it, you might want to search for some tool/add-on that can add automatically this check for you at compile time, like the PostSharp, Fody or alternatives.