我在多线程业务逻辑中运行以下代码:
using System;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var biz1 = new Biz { Some = 1, Value = "a" };
var biz2 = new Biz { Some = 2, Value = "b" };
var foo = new Foo();
//thread 1
new Task(() => foo.Run(biz1)).Start();
//thread 2
new Task(() => foo.Run(biz2)).Start();
//more threads here for other Biz objects....
Console.Read();
}
}
public class Biz
{
public int Some { get; set; }
public string Value { get; set; }
}
public class Foo
{
public void Run(Biz biz)
{
//base on the biz object do some task here
}
}
}
线程在biz
任何时候都不会更改对象
问题:
foo.Run
线程安全吗?- 实例化单个
Foo
对象以运行每个Biz
对象(这Run
是唯一的函数Foo
)会更好吗?