2012-08-15 142 views
-5

我正在使用一個使用返回消息字符串的函數的第三方庫。我的問題是我不知道在什麼時候會收到此消息,我需要在C#中構建一個應用程序,以在文本框中顯示消息。c#中的線程和循環(Windows窗體)

注:我可以在程序運行時收到'n'消息。

根據我讀的是我需要使用線程,但不是如何。

我試圖做到這一點,但沒有得到期望的結果:

Thread p1 = new Thread(new ThreadStart(myfuntion)); 
p1.Start(); 

public myfunction() 
{ 
    while (true) 
    { 
     textbox.text = myobj.messages; 
    } 
} 

請幫助!

+0

什麼樣的圖書館是什麼?是不是有一個事件通知你改變的消息?如果沒有,你需要設置一個['Timer'](http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx),每隔幾秒檢查一次新消息*(提示:無限循環不是方式)* – Adam 2012-08-15 06:35:00

+0

無法理解您的問題,您能否更清楚一點,如何在發佈新消息時使用事件訂閱者瞭解它? – 2012-08-15 06:36:02

+2

@lvanrlg什麼是'bucles'我第一次聽到它? – 2012-08-15 06:37:52

回答

0

您最好使用Task,並且您必須使用Invoke,因爲您無法從其他線程更新GUI。

Task.Factory.StartNew(myfunction); 

public void myfunction() 
{ 
    while (true) 
    { 
     textBox1.Invoke(new Action(() => textBox1.Text = myobj.messages)); 
    } 
} 

但是,我對這段代碼並不滿意。這段代碼總是更新gui。您可能希望在每次迭代之間等待Thread.Sleep(milliseconds),或者在庫中有某個內容向您發送消息時發送消息,而不必親自檢查。

+0

我拋出了這個錯誤:Error 1 Using the泛型類型('System.Action ')需要1個類型參數 – Ivanrlg 2012-08-15 13:46:41

+0

您需要使用System.Action,而不是System.Action 。 http://msdn.microsoft.com/en-us/library/system.action.aspx – 2012-08-15 13:55:16

0

我喜歡使用BackGroundWorker。線程仍然會導致鎖定,因爲線程將從窗體本身產生。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    { 
     // Do not access the form's BackgroundWorker reference directly. 
     // Instead use the reference provided by the sender parameter 
     BackgroundWorker bw = sender as BackgroundWorker; 

     // Extract the argument 
     RequestEntity arg = (RequestEntity)e.Argument; 

     // Start the time consuming operation 
     Poll poll = new Poll(); 
     e.Result = poll.pollandgetresult(bw, arg); 

     // If operation was cancelled by user 
     if (bw.CancellationPending) 
     { 
      e.Cancel = true; 
     } 
    } 

代碼項目以及好文章.... Read

0

由於您使用的一種形式,你可以使用System.Windows.Forms.Timer以一定的時間間隔。

private void StartPollingMessage() 
{ 
    System.Windows.Forms.Timer myTimer = new Timer(); 
    myTimer.Tick += new EventHandler(myTimer_Tick); 
    myTimer.Interval = 200; 
    myTimer.Start(); 
} 

void myTimer_Tick(object sender, EventArgs e) 
{ 
    textBox1.Text = myobj.messages; 
} 
0
void Main() 
{ 
    //this is the line when you start calling the external method 
    Parallel.Invoke(() => YourMethod); 
} 

public void YourMethod() 
{ 
    string s = ExternalMethod(); 
    //now you can use BackgroundWorker to update the UI or do the same thing as @Amiram Korach suggested 
} 

public string ExternalMethod() 
{ 
    Thread.Sleep(10000); // the operation to retrieve the string can take 1 hour for example 
    return "String that you want to retrieve"; 
} 

// Define other methods and classes here 
+0

如果您將收到的元素順序不相關,則可以使用Parrallel – Zinov 2015-09-20 19:19:58