考虑下面的伪代码。我有一个类,其中包含3个属性,每个属性都从不同的方法并行填充。将同一类实例的不同属性从单独的线程中填充是否会导致问题?我已经设置了一个{{link1:.net fiddle}},看起来它运行得很好。如果这段代码会引起线程问题,我应该使用哪种方法锁定Response类的特定实例,同时填充属性?
class Response {
public string Response1 { get; set; }
public string Response2 { get; set; }
public string Response3 { get; set; }
}
void foo() {
var response = new Response();
var task1 = Task.Run(() => GetResponse1(response));
var task2 = Task.Run(() => GetResponse2(response));
var task3 = Task.Run(() => GetResponse3(response));
Task.WaitAll(task1, task2, task3);
}
void GetResponse1(Response response) {
response.Response1 = fetchSomeValue1();
}
void GetResponse2(Response response) {
response.Response2 = fetchSomeValue2();
}
void GetResponse3(Response response) {
response.Response3 = fetchSomeValue3();
}