Given the following, what would be the best synchronization technician
* Please note that this an example model and there are much more things going on.
The shared resource is the instruments dictionary which is updated from 2 places:
(1) an inner value is being rapidly updated.
(2) the entire collection is refreshed.
public class Insturment
{
public Feed Feed{ get; set;}
}
static IDictionary<string,Instrument> instruments = new Dictionary<string,Instrument>();
// (1) This happens frequently
public void OnNewFeed(Feed feed)
{
instruments[feed.Symbol].Feed = feed;
}
// (2) happens every few hours ,or manually triggered at any given time
public void BuildInstruments()
{
foreach(var instrument in newInstruments)
{
instruments.AddOrUpdate(insturment.Symbol,insturment);
}
}
I thought of the same basic concept block threads on UpdateFeed() when the entire collection is being rebuilt using a manual reset event.
ManualResetEvent _mre = new ManualResetEvent(false);
public void OnNewFeed(Feed feed)
{
_mre.WaitOne();
instruments[feed.Symbol].Feed = feed;
}
public void BuildInstruments()
{
_mre.Reset();
foreach(var instrument in newInstruments)
{
instruments.AddOrUpdate(insturment.Symbol,insturment);
}
_mre.Set();
}
Or the same thing using any kind of Task wrapper and awaiting it. something like this construct : The anser by Stephen Cleary
- Side note I don't care about data integraty when reading from the dictionary. meaning i don't mind some one receiving non-updated values from the dictionary at any given point. I do mind the actual update from being lost for ever because i just replaced the entire instrument that was being updated.
Questions :
1) Can any one think of a better approach to synchronize the operations on instruments dictionary.
2) Is there any advantages of using async/await on a task wrapping the WaitHandle ? ( like the one described in the link above)