Consider the pseudo code below. I have a class with 3 properties and each gets populated from a different methods in parallel.
Would I get into trouble populating different properties of the same class instance from separate threads? I've setup a .net fiddle and it seems like it runs fine.
If this code would cause threading issues, what method should I use to lock the specific instance of the Response class while populating the properties?
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();
}