2016-05-11 33 views
0

編輯:我應該澄清,但我在Visual Studio中調試這兩個應用程序。所以,當我部署它時,會去Rasp Pi(這是帶有問題的應用程序),另一個是在本地機器上運行的控制檯應用程序。爲什麼在使用LINQ vs Regex時這個字符串只返回一次?

我不確定怎麼說這個問題,但在你的幫助下,我相信我可以把它變成一個更通用的問題。 在這一點上我有我的項目工作,但我不確定爲什麼我以前實現此字符串解析的方式不起作用。我想明白爲什麼。

設置:

我有一個控制檯應用程序,我可以寫一個命令到,並將其發送到物聯網中心,我國樹莓派然後讀取,解析命令,並執行功能。

 // Keep listening for messages    
     private async Task listenForMessageFromDeviceTask() 
     { 
      while (true) 
      { 
       var msg = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync(); 
       if (msg == null) continue; 

       Globals.ParseMsg(msg); 
      } 
     } 

解決方案:

Link to the current working class on GitHub

public static void ParseMsg(string msg) 
{ 
    // Split msg on whitespace sequences. 
    // This works great! I only need to retrieve the first word. 
    string[] firstWordInMsg = Regex.Split(msg, @"\s+"); 

     switch (firstWordInMsg[0]) 
     { 
      case "tween": 
       // Do something 
       break; 
      case "stop": 
       // Do something 
       break; 
     } 

問題:

Link to the non-working version on GitHub

public static void ParseMsg(string msg) 
{ 
    // This will only execute ONE time. I can send 10 messages, and it will 
    // only receive one. I now have to restart the app, and it can then     // receive the next message in the queue. 
    var first_word = FirstWordFromMessage(msg) 

    switch (first_word) 
    { 
     case "tween": 
      // Do something 
      break; 
     case "stop": 
      // Do something 
      break; 
    } 


    public string FirstWordFromMsg(string msg) 
    { 
    var firstWord = msg.Substring(0, msg.IndexOf(" ", StringComparison.Ordinal)); 

    return firstWord; 
    } 

我的理解: 當我使用第一個解決方案時,一切都很好。我可以發送10封郵件,該應用可以閱讀全部10封郵件。

隨着第二個實現,我只能讀取一條消息,然後我需要重新啓動應用程序。在這一點上,它還有9個要通過。然後我需要退出應用程序,重新啓動它,然後再有8個應用程序。

爲什麼會發生這種情況?

+0

你能創建應用程序的最小重複的例子? –

+0

如果字符串不包含空格,則第二種方法將引發異常。 – Lee

+0

目前還不清楚你在這裏得到什麼。 *「我需要重新啓動應用程序之前」*您正在調試嗎? – Liam

回答

1

您需要遍歷包含在words每條消息:

public static void ParseMsg(string msg) 
{ 
    string[] words = Regex.Split(msg, @"\s+"); 

    foreach (string word in words) 
    { 
     switch (word) 
     { 
      case "tween": 
       // Do something 
       break; 
      case "stop": 
       // Do something 
       break; 
     } 
    } 
} 
+0

我明白,如果我需要得到每一個字,這將是正確的方法。就目前而言,我只需要第一個單詞,所以我的底層示例正常工作。 但我不確定爲什麼我提供的第一個解決方案不起作用。 不過謝謝你! –

相關問題