I have a function that is kicked off by an event handler. In this function a new task is created and ran to set a global variable that I will need later, within another event handler.
There are a couple other functions between these two as well which don't change any of the variables used within these. But here is what it kind of looks like this.
private void EventWhereINeedTheGlobalVariableLater(object sender, Event e)
{
//...work...
need _variableIneed
//....more work...
}
private void EventWhereISetGlobalVariable(object sender, Event e)
{
//....work....
//...make cancellationToken...
//groups, isCommonalityGroup are other global variables already set.
Task.Factory.StartNew(() =>
{
// Clear variable to get new value
_variableIneed = null;
// Execute query to get new value
_variableIneed = _workingManager.GetValue(groups, isCommonalityGroup, cancellationToken);
RefreshView();
}, cancellationToken);
}
I'm running into race conditions where the variable I need _variableIneed
is null within the second event handler and it can't be. It works fine if I'm not flying through and trying to create enough events to crash the wpf program, but I need it work even if I do that.
Is there something I can do to get past these race conditions?
I've tried using the .ContinueWith
with the option of OnlyOnRanToCompletion
or whatever it is. Any other things I could try?
**Note I can't do a lot with changing how the events are ordered/handled/worked through. It's a pretty set in stone design and I just have to work around it and keep it more or less how it is.
**Update
I have also tried using the ParallelExtensionsExtras
with the OrderedTaskScheduler
class and I still end up getting a null reference on the variable I need.