In the below example, a call to HandleChangesAsync is made from within an asynchronous task, and via an event handler.
I'm concerned there's a potential race condition where one thread is executing the create_task block in HandleChangesAsync. While that's happening, the OnSomethingChanged handler fires, and a second thread ends up executing the same create_task block in HandleChangesAsync,
Question - Assuming this concern is legitimate, what's the right way to eliminate this race condition?
void MyClass::DoStuffAsync()
{
WeakReference weakThis(this);
create_task(DoMoreStuffAsync())
.then([weakThis]())
{
auto strongThis = weakThis.Resolve<HomePromotionTemplateViewModel>();
if (strongThis)
{
strongThis->RegisterForChanges();
strongThis->HandleChangesAsync();
}
});
}
void MyClass::RegisterForChanges()
{
// Attach event handler to &MyClass::OnSomethingChanged
}
void MyClass::OnSomethingChanged()
{
HandleChangesAsync();
}
void MyClass::HandleChangesAsync()
{
WeakReference weakThis(this);
create_task(DoMoreCoolStuffAsync())
.then([weakThis]())
{
// do stuff
});
}