I have a function similar to the following:
public void Increment()
{
if (Count == 0)
{
AttachResource();
}
Count++;
}
Changes to my code mean that this function will be called from multiple threads. Due to the nature of AttachResource(), this function must be run on the main thread.
Assume I modify the function to be as follows:
public void Increment()
{
_dispatcher.Invoke(new Action(() =>
{
if (Count == 0)
{
AttachResource();
}
Count++;
}));
}
Do I need to also add a lock to this code to ensure mutually exclusive access by threads? Or will the call through the dispatcher naturally accomplish this by serializing multiple calls onto the main thread?
Your examples will prevent AttachResource from being called more than once unless something else resets Count.
Other than that, assuming Dispatcher is the UI’s dispatcher instance (e.g.
Application.Current.Dispatcher), then only the UI thread will invoke AttachResource from this code path.