是线程调用回创建线程线程安全

本文关键字:线程 安全 创建 调用 | 更新日期: 2023-09-27 18:16:15

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

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");
        ...
    }
}

是线程调用回创建线程线程安全

您没有回调任何其他线程。

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

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

你的例子不是线程安全的,如果你想要线程安全,我非常建议使用BackgroundWorker在新线程中执行,但将消息发送回主线程。

例如:

class ThreadCreator
{
    private AnObject obj = new AnObject();
    public ThreadCreator()
    {
        for (int i = 0; i < 100; ++i)
        {
            ThingToThread th = new ThingToThread();
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += th.DoWork;
            worker.ProgressChanged += WorkerProgressChanged;
            worker.RunWorkerAsync();
        }
    }
    private void WorkerProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        string stuff = e.UserState as string;
        obj.DoThing(stuff);
    }
}

你的ThingToThread DoWork方法看起来像:

public void DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    worker.ReportProgress(50, "Half way there");
    worker.ReportProgress(100, "Finished");
}