Protecting shared isostorage data between app and background agent
Asked Answered
D

1

6

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?

Denims answered 16/4, 2012 at 20:16 Comment(0)
B
6

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.

Bootee answered 25/4, 2012 at 6:6 Comment(2)
Why do you create the Mutex with initiallyOwned true in one case and not the other?Denims
@JesperLarsen-Ledet initialOwned indicates whether the calling thread should have initial ownership of the mutexCoventry

© 2022 - 2024 — McMap. All rights reserved.