Skip to main content
 首页 » 编程设计

c#之线程回调创建线程线程安全吗

2024年02月23日16xiaohuochai

我不喜欢这段代码,但我总是对线程感到困惑,所以在我建议更改之前需要其他人的输入;这个线程安全吗(虽然是基于 C# 的伪代码):

class ThreadCreator 
{ 
    private AnObject obj = new AnObject(); 
    public ThreadCreator() 
    { 
        for (int i = 0; i < 100; ++i) 
        { 
            ThingToThread th = new ThingToThread();//don't care about losing ref to th for this question 
            th.sendMsg = this.getMessage; 
            Thread t = new Thread(th.doThing); 
            t.SetApartmentState(ApartmentState.STA); 
            t.Start(); 
        } 
    } 
 
    public void getMessage( string stuff ) 
    { 
        ... 
        obj.DoThing(stuff); 
        ... 
    } 
} 
 
class ThingToThread 
{ 
    public delegate void sendMsg(string stuff); 
 
    public void doThing() 
    { 
        ... 
        this.sendMsg("ohh that's interesting"); 
        ... 
    } 
} 

请您参考如下方法:

您不会回调任何其他线程。

您的代码将在新线程上执行委托(delegate),就像任何其他函数调用一样。

如果 getMessage 不是线程安全的,您的代码将会中断。