'How to prevent a class from being used in another thread
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
