使用Mutex时,从非同步块调用对象同步方法

时间:2014-06-05 07:25:53

标签: windows-runtime mutex windows-8.1 windows-phone-8.1

我正在尝试使用后台任务创建Windows通用应用程序。

我正在尝试编写触发进入蓝牙连接的后台任务。 防止前台和后台创建连接。我试图在前景和背景中实现相同的互斥。

当我从蓝牙设备读取数据时,我收到以下错误。

从非同步块

调用对象同步方法

令我惊讶的是偶尔出现此错误。我错过了什么吗?

这是我的代码:

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();


    }
   }

1 个答案:

答案 0 :(得分:0)

互斥锁必须在获取它的同一个线程上释放。 当您等待异步方法返回到相同的上下文时,不保证您返回到同一个线程。

改为使用信号量。