2012-01-10 88 views
0

我想在設備上收聽消息,並且從第一條消息顯示它在datagridview上看到第一條消息,但從設備獲取消息完美工作,但問題在於當我要設置DGV內容時,我得到了此異常跨線程操作無效,並且我已閱讀this相關主題。
但他們都沒有幫助,因爲沒有綁定DGV。
這裏是我的代碼: 1.首先我必須被綁定到DGV消息類,線程安全問題:跨線程操作無效

public class Msg_log 
{ 
    public Msg_log() 
    { 
     this.Event = null; 
     this.Operator = null; 
    } 
    public string Event { get; set; } 
    public string Operator { get; set; } 
} 

,這裏是如何創建的loadform事件另一個線程:

newThread = new System.Threading.Thread(this.Event_Listener); 
     newThread.Start(); 

並在Event_Listener功能

   x.Add(message); 
       MsgDGV.DataSource = null; 
       MsgDGV.DataSource = x; 
       MsgDGV.Refresh(); 

消息對象是這樣的:

Msg_log message = new Msg_log(); 

及其消息的事件和運算符變量已被正確設置,並且我將MSG.DataSource = null,因爲我想在新消息正在提交後更新我的DGV(實際上,這是我的想法,如果有的話是更好的方式,我會明白這一點),這是我得到的豁免線:跨線程操作無效。在其他帖子中,我發現我應該使用Invoke方法,但我不知道如何調用Msg_DGV.Invoke(??,???);我不知道我應該怎麼傳遞給得到正確的結果...
乾杯,

+0

創建一個方法來處理設置DGV數據源和刷新到DGV並調用MsgDGV.Invoke(myDelegate,vnew Object [] {x}); http://msdn.microsoft.com/en-us/library/a1hetckb – Lloyd 2012-01-10 11:20:12

回答

1

你做想做的事一樣的,你鏈接到這個職位,只是改變你的控制使用一個DataGridView。 C# Thread issues

Msg_DGV.Invoke(new Action(() => Msg_DGV.DataSource = null)); 

here不使用操作的更完全成熟的例子。

// The declaration of the textbox. 
private TextBox m_TextBox; 

// Updates the textbox text. 
private void UpdateText(string text) 
{ 
    // Set the textbox text. 
    m_TextBox.Text = text; 
} 

//Now, create a delegate that has the same signature as the method that was previously defined: 
public delegate void UpdateTextCallback(string text); 

//In your thread, you can call the Invoke method on m_TextBox, 
//passing the delegate to call, as well as the parameters. 
m_TextBox.Invoke(new UpdateTextCallback(this.UpdateText), 
      new object[]{」Text generated on non-UI thread.」}); 
+0

我做到了這一點,這有助於我認爲:) Action show_DGV = delegate() { MsgDGV.DataSource = null; MsgDGV.DataSource = x; MsgDGV.Refresh(); }; this.MsgDGV.Invoke(show_DGV); – Ehsan 2012-01-10 11:24:35

1

您可以使用BackgroundWorker。

var bw = new BackgroundWorker(); 
bw.DoWork += (s, e) => { 
         ... 
         x.Add(message); 
         ... 
         e.Result = x; 
         }; 
bw.RunWorkerCompleted += (s, e) => MsgDGV.DataSource = e.Result; 
bw.RunWorkerAsync();