【发布时间】:2022-02-24 13:23:09
【问题描述】:
我有一个只想在一个线程中使用的类。如果我在一个线程中创建该类的对象并在另一个线程中使用它,则会导致很多问题。目前,我这样解决这个问题: 我有 Context 类,我只想在一个线程中使用它:
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
}
这里是学生类中Context类的用法:
public class Student
{
Context context;
public Context Context
{
get
{
if (context == null)
context = new Context();
context.AssertThread();
return context;
}
}
}
当我在不同的线程中使用上下文时,它会抛出一个错误:
var student = new Student();
var context = student.Context;
Task.Run(() =>
{
var context = student.Context;//InvalidOperationException
});
但是这个解决方案并不可靠。例如,当我有另一个使用上下文的类时,我需要在获取上下文属性时执行 AssertThread。或者当我在一个新变量中获取上下文并在不同的线程中使用它时,我的异常不会被抛出。那么,是否有任何解决方案可以强制类仅在一个线程中使用?
【问题讨论】:
-
在类的每个公共方法和属性的开头添加
AssertThread()怎么样? -
@TheodorZoulias 这可能是一个解决方案,但不是很好。会很乱。是否有任何标准的方法,或者也许有人做了同样的工作
-
在这里查看 Marc Graville 的答案:stackoverflow.com/a/20609176/495455
-
也许 Semaphore 或 SemaphoreSlim 可能是一个解决方案?
标签: c# multithreading