mardi 15 mai 2018

Patterns to synchronize access

In my app I have an item service with operations on items (surprise!). The service is used by view-models bound to views (using MVVM here) to update items in different ways.

The app has a background service which receives notifications from backend. It also uses the item service, it calls the item service to get some item information and based on the result (item state), call item service to update item.

The issue is how to synchronize access to the items, since there's two threads (item service thread and background service thread) both with operations on items.

Should the item service have synchronization inside?

Sometimes is not so simple. The logic in background service is interleaving with calls to the items service:

On background service:

var item = itemService.getItemBySomeCondition();
if(item != null)
{
   DoSomething(); // background service specific logic

   itemService.SomeOperation(item);

   DoSomething2();  // background service specific logic

   itemService.SomeOtherOperation(item);
}

If all the logic was inside the item service I know I could use some simple locking mechanism to synchronize operations inside of the item service.

I am using C# and .NET in case you have specific suggestions on which classes or patterns to use. Beside answering, I'd appreciate if you have some reference I could read (tutorials\books) on recommended patterns for this kind of problems

Aucun commentaire:

Enregistrer un commentaire