2014-05-18 21 views
0

我一直在努力使這項工作沒有成功。Windows應用商店中RFComm通信的工作流程

我有第三方設備將由我的Windows應用商店通過藍牙控制。問題是通信方法的異步等待性質。

當某個頁面加載時,該應用將首先啓動連接。它將使用此代碼來啓動連接:

public async Task Test() 
    { 
     var loadedDevices = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); 

     var foundDevice = loadedDevices.FirstOrDefault(x => x.Name == "DEVICE_NAME"); 

     if (foundDevice != null) 
     { 

      var connection = getConnection(foundDevice); 
     } 

    } 

    public async Task<RfcommDeviceService> getConnection(DeviceInformation device) 
    { 
     return await RfcommDeviceService.FromIdAsync(device.Id); 
    } 

我沒有將它與我的應用程序分開,因爲它只是無法正常工作。

獲得連接後,我需要從連接流中獲取DataWriter和DataReader。

藍牙設備有一個協議,我們寫東西,然後讀取響應。但它的機制也是異步方法。 要寫出我用這個方法的命令:

private void SendCommand(string command) 
    { 
     Task.Run(async() => { await this.writer.FlushAsync(); }).Wait(); 
     this.writer.WriteString(command); 
     Task.Run(async() => { await this.writer.StoreAsync(); }).Wait(); 
    } 

,並閱讀,我一會就好這裏面讀取數據:

while (!data.EndsWith("\n")) 
     { 
      uint messageLength = this.reader.UnconsumedBufferLength; 
      uint nbytes = 0; 

      Task.Run(async() => { nbytes = await this.reader.LoadAsync(1024); }).Wait(); 

      if (nbytes == 0) 
      { 
       iterates++; 
       continue; 
      } 

      if (iterates > 3) 
      { 
       break; 
      } 

      iterates = 0; 
      data += this.reader.ReadString(this.reader.UnconsumedBufferLength); 
     } 

的問題是,有時,我不知道爲什麼連接起作用,有時不起作用。 有時它跨越連接或寫或讀方法忽略調用並在任何地方返回null。

請問,有關使用RFComm設備處理異步/等待的最佳做法的任何幫助?

我讀過很多東西,這裏和那裏的問題,但似乎我缺乏基礎(我在MSDN讀取)或解釋。

任何幫助非常感謝!

感謝

回答

1

當你await它在後臺線程已經執行異步操作,你不需要添加Task.Run。所以下面的代碼:

Task.Run(async() => { nbytes = await this.reader.LoadAsync(1024); }).Wait(); 

可以寫爲:

nbytes = await this.reader.LoadAsync(1024); 

你也不需要調用Wait,因爲這是一個阻塞操作,並在操作完成前將阻止當前線程。又如方法SendCommand

private void SendCommand(string command) 
{ 
    await this.writer.FlushAsync(); 
    this.writer.WriteString(command); 
    await this.writer.StoreAsync(); 
} 

SendCommand的方法將在操作完成之前的await有效地「暫停」的方法按順序執行。我認爲你需要更多地瞭解async/await。這article可能會有所幫助。

+0

Hey Ned,謝謝你的回答。我想讀取您要發佈的資源,但我認爲您忘記了[文章] [1]上的鏈接。你可以寄出嗎? – Ralph

+0

對不起,現在應該是好的。 –

+0

沒關係,謝謝。我會再讀一遍(已經完成),但我可能會錯過一些東西。謝謝! – Ralph