Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protecting shared isostorage data between app and background agent

According to MSDN communication between foreground app and background agents through files in isolated storage should be protected by a Mutex.

The only article I can find that describes how to do this is this one by Dina Berry. However, she only appears to protect the reads with the Mutex and not the writes.

What is the correct way to do this?

like image 543
Jesper Larsen-Ledet Avatar asked Apr 16 '12 20:04

Jesper Larsen-Ledet


1 Answers

A mutex can lock across multiple processes. This would be useful in Windows Phone if you have a scheduled task running that needs exclusive access to a resource. In order to lock a mutex across processes the Mutex must be given a name.

A monitor can lock only within a process.

Mutex Example:

Phone App Task:

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're only allowing one app at a time access to the local database resource. This is why we'd use a Mutex.

Monitor Example (using lock syntax):

Phone App Task:

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 thread entering SaveRow and we can stop more than one ScheduledTask thread from entering the DoStuff method. What we can't do with a Monitor is ensure that only one thread is accessing the local DB at once.

That's basically the difference. Monitor is much faster than a Mutex as well.

like image 149
Rakesh R Nair Avatar answered Oct 26 '22 13:10

Rakesh R Nair