2015-01-04 37 views
0

有一個奇怪的問題,無法解決它。使用BackGroundWorker調用控件

嘗試在我的應用程序中將RichTextBox轉換爲日誌「控制檯」。當然,我在我的應用程序中使用線程,當然我知道Invoke。

讓我們來看看我的代碼。

MainForm開始BackGroundWorker做這項工作。我的BackGroundWorker啓動了很多線程,在事件中調用DebugConsole。對於這個問題,我舉一個簡單的例子。

bkw.DoWork += (obj, a) => DebugConsole.DoSomeWork(msg, Color.Coral); 
bkw.RunWorkerAsync(); 

DebugConsole是我實現一個Singleton模式讓我DoSomeWork函數的類。

讓我們看看DebugConsole類:

class DebugConsole 
{ 
     private static readonly DebugConsole instance = new DebugConsole(); 

     public static DebugConsole Instance 
     { 
      get { return instance; } 
     } 

     public static void DoSomeWork(string msg, Color color) 
     { 
      Instance.DebugBox(msg, color); 
     } 

     private void DebugBox(string msg, Color color) 
     { 
      MainForm.DoSomeWork(msg, color); 
     } 
    } 

而且還有你看我MainForm也Singleton模式來實現調用的下一個想法。

private static readonly MainForm instance = new MainForm(); 

public static MainForm Instance 
{ 
    get { return instance; } 
} 

public static void DoSomeWork(string ev, Color clr) 
{ 
    Instance.LogTextEvent(ev,clr); 
} 

LogTextEvent做我的應用程序的最後想,在我的RichTextBox寫一條消息,這就是問題所在。它不寫/調用我的控件。

public void LogTextEvent(string eventText, Color textColor) 
{ 
     var nDateTime = DateTime.Now.ToString("hh:mm:ss tt") + " - "; 
     if (rtbDebug.InvokeRequired) 
     { 
      rtbDebug.BeginInvoke((MethodInvoker) delegate 
      { 
       rtbDebug.SelectionStart = rtbDebug.Text.Length; 
       rtbDebug.SelectionColor = textColor; 

       if (rtbDebug.Lines.Length == 0) 
       { 
        rtbDebug.AppendText(nDateTime + eventText); 
        rtbDebug.ScrollToCaret(); 
        rtbDebug.AppendText(Environment.NewLine); 
       } 
       else 
       { 
        rtbDebug.AppendText(nDateTime 
             + eventText 
             + Environment.NewLine); 
        rtbDebug.ScrollToCaret(); 
       } 
      }); 
     } 
     else 
     { 
      rtbDebug.SelectionStart = rtbDebug.Text.Length; 
      rtbDebug.SelectionColor = textColor; 

      if (rtbDebug.Lines.Length == 0) 
      { 
       rtbDebug.AppendText(nDateTime + eventText); 
       rtbDebug.ScrollToCaret(); 
       rtbDebug.AppendText(Environment.NewLine); 
      } 
      else 
      { 
       rtbDebug.AppendText(nDateTime 
            + eventText 
            + Environment.NewLine); 
       rtbDebug.ScrollToCaret(); 
      } 
     } 
    } 

問題:在我的控制中沒有任何反應。

  • 我在做什麼錯?
  • 有人能告訴我我失蹤了什麼嗎?
+0

你有沒有使用Visual Studio調試器,找出哪些代碼實際上執行? –

+0

當然我用VS來調試...所有的代碼似乎工作正常 – Johnny

+0

鑑於:你的代碼不能做你想做的事情,而當你調試它似乎是做你想做的事情時,它一定是這樣的情況你沒有正確地調試問題(即濫用調試器,從而無法識別錯誤)。當然,如果沒有完整的代碼示例,沒有其他人可以代表您進行任何調試。我在您發佈的代碼中看到的最大問題是調用的複製/粘貼。但是在這種情況下,沒有什麼能夠表明實際的問題。您需要[改進代碼示例](https://stackoverflow.com/help/mcve)或改進您的調試。 :) –

回答

-1

試試這個

this.Invoke((MethodInvoker)delegate 
     { 
      Instance.LogTextEvent(ev,clr); 
     }); 
+0

執行'LogTextEvent'編組到UI線程的執行。 – Servy

相關問題