加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Windows Phone – 使用互斥锁进行隔离存储

发布时间:2020-12-15 21:57:13 所属栏目:百科 来源:网络整理
导读:我试图用互斥锁保护我的隔离存储,以便我可以从移动应用程序和BackgroundAudioPlayer访问它. 这些是我在isosorage中访问文件的助手类: public static async Task WriteToFile(string text) { using (var mut = new Mutex(false,"IsoStorageMutex")) { mut.Wa
我试图用互斥锁保护我的隔离存储,以便我可以从移动应用程序和BackgroundAudioPlayer访问它.

这些是我在isosorage中访问文件的助手类:

public static async Task WriteToFile(string text)
    {
        using (var mut = new Mutex(false,"IsoStorageMutex"))
        {
            mut.WaitOne();
            try
            {
                // Get the text data from the textbox. 
                byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(text.ToCharArray());

                // Get the local folder.
                var local = ApplicationData.Current.LocalFolder;

                // Create a new folder name DataFolder.
                var dataFolder = await local.CreateFolderAsync("MusicFolder",CreationCollisionOption.OpenIfExists);

                // Create a new file named DataFile.txt.
                var file = await dataFolder.CreateFileAsync("Streams.txt",CreationCollisionOption.ReplaceExisting);

                // Write the data from the textbox.
                using (var s = await file.OpenStreamForWriteAsync())
                {
                    s.Write(fileBytes,fileBytes.Length);
                }
            }
            finally
            {
                mut.ReleaseMutex();
            }
        }
    }

    public static async Task<string> ReadFile()
    {
        using (var mut = new Mutex(false,"IsoStorageMutex"))
        {
              mut.WaitOne();
              var result = String.Empty;
              try
              {
                  // Get the local folder.
                  var local = ApplicationData.Current.LocalFolder;

                  if (local != null)
                  {
                      // Get the DataFolder folder.
                      var dataFolder = await local.GetFolderAsync("MusicFolder");

                      // Get the file.
                      var file = await dataFolder.OpenStreamForReadAsync("Streams.txt");

                      // Read the data.

                      using (var streamReader = new StreamReader(file))
                      {
                          result = streamReader.ReadToEnd();
                      }
                  }
              }
              finally
              {
                  mut.ReleaseMutex();
              }
              return result;
        }
    }

但是当我尝试在后台代理中访问它时,我收到此错误:

Object synchronization method was called from an unsynchronized block of code.

堆栈跟踪:

at System.Threading.Mutex.ReleaseMutex()
   at YouRadio.IsolatedStorage.StorageHelpers.<ReadFile>d__b.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at YouRadio.AudioPlaybackAgent.AudioPlayer.<AddTracksFromIsoStorageToPlaylist>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at YouRadio.AudioPlaybackAgent.AudioPlayer.<OnUserAction>d__2.MoveNext()

我做错了什么?

解决方法

你正在以错误的方式实现Mutex.您应该在IsolatedStorageHelper类中创建它的全局实例,并使用该实例创建方法.

public class IsolatedStorageHelper
{
    private static Mutex mut = new Mutex(false,"IsoStorageMutex");

    public static async Task WriteToFile(string text)
    {
        mut.WaitOne();
        try
        {
            ...
        }
        finally
        {
            mut.ReleaseMutex();
        }
    }

    public static async Task<string> ReadFile()
    {
          mut.WaitOne();
          var result = String.Empty;
          try
          {
              ...
          }
          finally
          {
              mut.ReleaseMutex();
          }
          return result;
    }
}

互斥锁具有线程关联性,互斥锁的所有者是线程.获取它的线程也必须是调用ReleaseMutex()的线程.打破这使得这个令人讨厌的异常被抛出.

根据您的要求,您可能还有不同的互斥锁用于读写文件.此外,如果所有方法在您的类中都是静态的,您可以将它设为单例类.这样你就可以有一个私有构造函数来初始化互斥和其他东西.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读