首页 > 解决方案 > 来自线程外部定义的对象的线程中的方法调用会以线程方式运行吗?

问题描述

即使这个方法是在线程外定义的,它会在线程中运行还是并行运行?除了比赛条件之外,还会有任何副作用吗?

SomeClass a = new SomeClass()
ThreadStart childref = new ThreadStart(() =>
{
    a.mass = a.CalculateMass() // Lets say this takes a minute to calculate.
});

Thread childThread = new Thread(childref);
childThread.Start();

标签: c#multithreading

解决方案


它将在单独的线程中运行。

变量只是内存中仅受进程而非线程限制的位置。因此,应用程序中的单独线程可以访问内存中的相同位置。

如果您不注意确保在任何时候只有一个线程访问它,那么除了竞争条件之外不会有其他副作用。


推荐阅读