(Note: I already asked this question, but the answer was specific to Java, and so I am asking the same question for C# and the .NET framework. It is NOT a duplicate.)
I have been using this pattern for a while, but I only recently came to think that it might not be OK to do this. Basically, I use some variant of this pattern:
public class SampleAsync
{
public SampleAsync() { }
private bool completed;
public void Start()
{
var worker = new BackgroundWorker();
worker.DoWork += (sender, e) => {
//... do something on a different thread
completed = true;
};
worker.RunWorkerAsync();
}
public void Update()
{
if (!completed) return;
//... do something else
}
}
*The user is responsible for making sure Start
is only called once. Update
is called wherever and whenever.
I've always assumed this is threadsafe in C#/the .NET framework, because even though nothing is strictly synchronized, I only ever set completed
to true. Once it has been observed to be true
, it will not reset to false
. It is initialized to false in the constructor, which is by definition thread safe (unless you do something stupid in it). So, is it thread safe to use unresettable flags in this way? (And if so, does it even provide any performance benefits?)
Thanks