Protect isostorage shared data between application and background agent

According to MSDN, communication between the front-end application and background agents via files in isolated storage must be protected with Mutex.

The only article I can find describes how to do this , this Dina Berry. However, it only protects reads with Mutex, not write.

What is the right way to do this?

+6
source share
1 answer

A mutex can block multiple processes. This would be useful on Windows Phone if you have a scheduled task that requires exclusive access to the resource. To block a mutex through processes, Mutex must have a name.

The monitor can only be locked inside the process.

Mutex example:

The task of the application for the phone:

public class DatabaseService { private Mutex _mut=new Mutex("mutex control",false); public void AddToDatabase(DbObject row) { mut.WaitOne(); SaveRow(row); mut.ReleaseMutex(); } } 

Scheduled task class:

 public class ResourceUtilisation { private Mutex _mut=new Mutex("mutex control",true); //.. does stuff private static void UseResource() { // Wait until it is safe to enter. _mut.WaitOne(); //Go get dataabse and add some rows DoStuff(); // Release the Mutex. _mut.ReleaseMutex(); } } 

In the above example, we allow only one application to access the local database resource. That is why we will use Mutex.

Monitor example (using lock syntax):

The task of the application for the phone:

 public class DatabaseService { private object _locker=new object(); public void AddToDatabase(DbObject row) { lock(_locker) SaveRow(row); } } 

Scheduled task class:

 public class ResourceUtilisation { private object _locker=new object(); //.. does stuff private static void UseResource() { //Go get dataabse and add some rows lock(_locker) DoStuff(); } } 

In this example, we can stop more than one application that is part of SaveRow, and we can stop more than one ScheduledTask thread from entering the DoStuff method. What we cannot do with the monitor ensures that only one thread accesses the local database at once.

This is basically the difference. The monitor is much faster than Mutex.

+6
source

Source: https://habr.com/ru/post/913360/


All Articles