C
C#3mo ago
ChezZ

Question regarding thread safety

Is it safe to call code on the foo object from multiple threads in this scenario? Like what happens if two threads try to access the foo object to call DoSomething() on instanceA at the same time?
static void Main()
{
var foo = new Foo();
foo.instanceA = new Bar();
foo.instanceB = new Bar();

//Assuming every method on Bar is thread safe is it safe to access the foo object to call a method on Bar from any thread?
foo.instanceA.DoSomething();


}
public class Foo
{
public Bar instanceA;
public Bar instanceB;
}

public class Bar
{
public void DoSomething()
{

}
}
static void Main()
{
var foo = new Foo();
foo.instanceA = new Bar();
foo.instanceB = new Bar();

//Assuming every method on Bar is thread safe is it safe to access the foo object to call a method on Bar from any thread?
foo.instanceA.DoSomething();


}
public class Foo
{
public Bar instanceA;
public Bar instanceB;
}

public class Bar
{
public void DoSomething()
{

}
}
7 Replies
Izagawd
Izagawd3mo ago
it will still execute from multiple threads, i believe. if there are parts of the method you dont want to be executed in multiple threads, you can use lock
kurumi
kurumi3mo ago
it is safe unless you don't use shared data (in case if both threads used it for reading, it's fine)
ChezZ
ChezZ3mo ago
Could you elaborate a little what you mean? I know the code going on in DoSomething is thread safe im just worried if the foo object is going to cause any issues executing it
kurumi
kurumi3mo ago
I mean that executing DoSomething is thread safe it doesn't matter in which instance it's called. Unless you have shared state that any thread can interrupt
ChezZ
ChezZ3mo ago
so if i was to spin up two threads i could call foo.instanceA.DoSomething() from both the threads?
kurumi
kurumi3mo ago
yes, you can
ChezZ
ChezZ3mo ago
Alright thank you very much so I guess calling a method on object references is just a read operation?
Want results from more Discord servers?
Add your server