Reputation: 485
I cant'find an answer to this simple question: is BeginInvoke() guaranteed to execute atomically the called delegate? For instance, if I have something like
public ObservableCollection<string> Items;
public int TotalLenght;
delegate void AddItemDelegate(string arg);
Dispatcher _dispatcher=Dispatcher.CurrentDispatcher;
void StartExecute()
{
for (int index = 0; index < 10; index++)
{
Thread th=new Thread(Run);
th.Start();
}
}
void Run()
{
string item = DoLongRandomDuringCalculations();
_dispatcher.BeginInvoke(new AddItemDelegate(AddItem), item);
}
void AddItem(string item)
{
Items.Add(item);
TotalLength += item.Length;
TakeSnapshot();
}
can I stay assured that updates to the collection and the other member always are in sync, also if a calculation thread calls BeginInvoke exactly while another thread is in the middle of updating?
Upvotes: 2
Views: 307
Reputation: 941465
You'll get strong guarantees from the fact that all invoked methods run on the same thread. So by design they must run in order and can never overlap. So the Items collection is entirely safe and no locking is required, atomicity is not an issue.
The exact order of items in the collection when the threads complete is however entirely non-deterministic.
Upvotes: 3