2015-04-20 29 views
0

所以我需要更新我的WPF UI,以下是相同的代碼。這更新和UI中的元素。 使用此處指出的第三方UI庫創建commandPrompt對象:http://www.codeproject.com/Articles/247280/WPF-Command-Prompt。我正在測試這個UI模型。 它拋出下面的異常:由於單獨的線程所有權,調用線程無法訪問對象

,因爲不同的 線程擁有它調用線程不能訪問該對象。

private void CommandProcess(object sender, ConsoleReadLineEventArgs EventArgs) 
     { 
      string[] command = new string[EventArgs.Commands.Length]; 

      for (int i = 0; i < EventArgs.Commands.Length; i++) 
      { 
       command[i] = EventArgs.Commands[i].ToLower(); 
      } 
      if (command.Length > 0) 
      { 
       try 
       {      
        switch (command[0]) 
        { 
         case "clear": 
          ProcessClear(command); 
          break; 
         case "demo": 
          ProcessParagraph(command); 
          break; 

         default: 
          new Task(() => { TextQuery(command); }).Start();       
          break; 
        } 
       } 
       catch (Exception ex) 
       { 
        WriteToConsole(new ConsoleWriteLineEventArgs("Console Error: \r" + ex.Message)); 
       } 
      } 
     } 

這是TextQuery方法。這使用RestSharp.dll進行通信。

private void TextQuery(string[] command) 
    { 
     string APIQuery = ConvertStringArrayToString(command); 

     USBM usbm = new USBM("XXXXXX"); 

     QueryResult results = usbm.Query(APIQuery); 
     if (results != null) 
     { 
      foreach (Pod pod in results.Pods) 
      { 
       Console.WriteLine(pod.Title); 
       if (pod.SubPods != null) 
       { 
        foreach (SubPod subPod in pod.SubPods) 
        { 
       EXCEPTION?? ====>WriteToConsole(new ConsoleWriteLineEventArgs("" + subPod.Title + "\n" + subPod.Plaintext)); 

        } 
       } 
      } 
     } 
    } 

這是用於寫入同一自定義控制檯的功能。

private void WriteToConsole(ConsoleWriteLineEventArgs e) 
{ 
      commandPrompt.OnConsoleWriteEvent(this, e); <=======EXCEPTION HERE 
} 

如何讓線程在它們之間共享數據?我谷歌它,但真的不能讓我工作,因爲我是異步編碼的新手。

謝謝。

+2

您需要發佈更多的代碼。看來你需要使用Dispatcher來調用UI線程上的一些工作。 – Andrew

+2

哪行引發異常? – Neil

+0

添加了一些細節。請告訴是否需要更多。 –

回答

2

由於WriteToConsole調用commandPrompt,它訪問UI元素,應該在UI線程上進行調用。

由於您使用Task,您最終將使用另一個線程從中調用UI。這是不允許的,並會給你你得到的錯誤。

你應該叫Dispatcher.InvokeBeginInvoke使UI線程上的呼叫:

Application.Current.Dispatcher.BeginInvoke 
(new Action(() => 
     WriteToConsole(new ConsoleWriteLineEventArgs(subPod.Title + "\n" + subPod.Plaintext))) 
, DispatcherPriority.Background 
); 
+0

你可以顯示一些代碼?我似乎無法使其工作? –

+0

謝謝!你是最棒的! –

相關問題