2014-06-05 49 views
1

我正在嘗試創建具有後臺任務的Windows通用應用程序。對象同步方法在使用Mutex時從非同步塊調用

我想寫一個後臺任務,觸發一個傳入的藍牙連接。 防止前景和背景創建連接。我正試圖在前景和背景中實現相同的互斥量。

當我從藍牙設備讀取數據時,出現以下錯誤。

對象同步方法從非同步塊

讓我驚訝的叫這個錯誤出現偶爾。我錯過了什麼?

這裏是我的代碼:

public sealed class RFBackgroundTask : IBackgroundTask 
{ 

     .... Variable declarations 

    public async void Run(IBackgroundTaskInstance taskInstance) 
    { 

     BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); 
     try 
     { 
      taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled); 
      Debug.WriteLine("RFComm Task Running"); 
      hotwatchConnection = taskInstance.TriggerDetails as RfcommConnectionTriggerDetails; 
      socket = hotwatchConnection.Socket; 
      reader = new DataReader(socket.InputStream); 
      // n = new Notification(hotwatchConnection.RemoteDevice.HostName); 
      await Read(); 
     } 
     catch (System.Exception e) 
     { 
      Debug.WriteLine("RFComm Task Error: {0}", e.Message); 
      if (ismutexReleased == false) 
      { 
       Debug.WriteLine("Releaseing mutex because of error {0}:", e.Message); 
       connectionMutex.ReleaseMutex(); 
       ismutexReleased = true; 
      } 
     } 
     finally 
     { 
      if (ismutexReleased == false) 
      { 
       Debug.WriteLine("Releasing Mutex 2"); 
       connectionMutex.ReleaseMutex(); 
      } 
      ismutexReleased = true; 
     } 
     deferral.Complete(); 

    } 

    public IAsyncAction Read() 
    { 
     return Task.Run(async() => 
     { 
      try 
      { 
       connectionMutex = new Mutex(false, CONNECTION_MUTEX_NAME); 
       // Attempt to wait for the mutex 
       var waitResult = connectionMutex.WaitOne(); 
       if (waitResult) 
       { 
        Debug.WriteLine("Aquired Mutex Successfully"); 
       } 
       // If the wait was not successful, fail the connect operation 
       if (!waitResult) { throw new TimeoutException(); } 

       if (reader != null) 
       { 
        uint length = 500; 
        reader.InputStreamOptions = InputStreamOptions.Partial; 
        uint len = await reader.LoadAsync(length); 
        String message = reader.ReadString(len); 
        Debug.WriteLine("Read " + message + " In the First Attemnpt"); 
        var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings; 
        roamingSettings.Values["COMMAND"] = message; 
        //if(!message.StartsWith("01")) 
        //{ 
        // await ProcessCommand(message); 
        //} 
       } 
       reader.Dispose(); 
       socket.Dispose(); 
       socket = null; 
       if (waitResult == true) 
        connectionMutex.ReleaseMutex(); 
       ismutexReleased = true; 
       Debug.WriteLine("Released Mutex successfully after reading data"); 
      } 
      catch (Exception e) 
      { 

       Debug.WriteLine(e.Message); 
       if (ismutexReleased == false) 
       { 
        Debug.WriteLine("Releaseing mutex because of error {0}:", e.Message); 
        connectionMutex.ReleaseMutex(); 
        ismutexReleased = true; 
       } 
       throw; 
      } 
      finally 
      { 
       if (ismutexReleased == false) 
       { 
        connectionMutex.ReleaseMutex(); 
        Debug.WriteLine("Releasing Mutex"); 
       } 
       ismutexReleased = true; 
      } 

     }).AsAsyncAction(); 


    } 
    } 

回答

0

互斥必須在同一個線程,它被收購上公佈。 當您等待異步方法時,您將返回到相同的上下文,但不能保證返回到同一個線程。

改爲使用信號量。

相關問題