我试图在powershell singelton类中使用ThreadStaticAttribute为每个线程创建一个新的对象实例,但不起作用。
class log {
[ThreadStaticAttribute()]
static [log] $logging;
log(){
}
static [log]GetInstance(){
if($null -eq [log]::logging){
[log]::logging=[log]::New()
}
return [log]::logging
}
}这将为新创建的线程返回相同的对象,而不是实例化新的线程。有什么想法吗?
发布于 2019-05-10 00:51:50
我没有理由去尝试这个方法,但是很久以前我确实想到了它。我用来处理它的资源是下面的,但同样,我从来没有真正做到这一点,因为事情发生了变化,没有理由这样做。
ThreadStaticattribute表示变量的每个线程都有一个实例。这是静态变量的变体。
在程序的整个生命周期中,静态变量只有一个实例。标记为ThreadStatichas的变量,程序中的每个线程一个实例。
有关更多详细信息,请参阅示例。
class Program
{
public static Int32 singleton = 0;
[ThreadStatic]
public static Int32 threadSingleton = 0;
static void Main(string[] args)
{
Program executingProgram = new Program();
Thread firstThread = new Thread(new ThreadStart(executingProgram.FirstThread));
Thread secondThread = new Thread(new ThreadStart(executingProgram.SecondThread));
firstThread.Start();
firstThread.Join();
secondThread.Start();
firstThread.Join();
Console.Read();
}
public void FirstThread()
{
singleton++;
threadSingleton++;
Console.WriteLine("Singleton = {0} ThreadSingleton = {1}", singleton.ToString(), threadSingleton.ToString());
}
public void SecondThread()
{
singleton++;
threadSingleton++;
Console.WriteLine("Singleton = {0} ThreadSingleton = {1}", singleton.ToString(), threadSingleton.ToString());
}
}
# Output
Singleton = 1 ThreadSingleton = 1
Singleton = 2 ThreadSingleton = 1https://stackoverflow.com/questions/56059551
复制相似问题