我想了解如何定期更新我的GUI與一個簡單的文本字符串。從本質上講,我正在寫一個twitter應用程序,它定期輪詢twitter的更新。我希望更新的內容以文本塊的形式顯示在一個常量循環中。從後臺工作人員或事件更新GUI
爲了保持GUI響應,我需要在後臺工作線程中執行查詢,但是無法從此線程更新GUI。作爲一名學習者,我正在努力實現一種通過使用事件來更新GUI的方式。
在我下面的代碼中,我讚賞'MainWindowGoUpdate'將會出現在'錯誤的線程'上,但我怎樣才能獲得GUI線程來監聽事件呢?
一個指針讚賞。
public partial class MainWindow : Window
{
public MainWindow()
{
public static event UpdateTimeLineEvent _goUpdate;
public static string TheTimeLine;
UpdateTimeLine();
}
private void UpdateTimeLine()
{
txtb_timeline.Text = "Updating...";
BackgroundWorker startTimelineUpdater = new BackgroundWorker();
startTimelineUpdater.DoWork += new DoWorkEventHandler(startTimelineUpdater_DoWork);
startTimelineUpdater.RunWorkerCompleted += new RunWorkerCompletedEventHandler(startTimelineUpdater_RunWorkerCompleted);
startTimelineUpdater.RunWorkerAsync();
}
void startTimelineUpdater_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
Xtweet getSQL = new Xtweet();
var sqlset = getSQL.CollectLocalTimelineSql();
int i = 0;
while (i < 10)
{
foreach (var stringse in sqlset)
{
StringBuilder sb = new StringBuilder();
sb.Append(stringse[0] + ": ");
sb.Append(stringse[1] + " @ ");
sb.Append(stringse[2]);
sb.Append("\n");
TheTimeLine = sb.ToString();
_goUpdate += new UpdateTimeLineEvent(MainWindowGoUpdate);
_goUpdate.Invoke();
Thread.Sleep(10000);
i++;
}
}
}
}
void MainWindowGoUpdate()
{
txtb_timeline.Text = TheTimeLine;
}
void startTimelineUpdater_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
txtb_timeline.Text = "should not see this";
}
}
SO已經充滿了數以萬計的這方面的問題。我想你的獨特之處在於你在工作線程中訂閱事件處理程序,而不是在啓動它之前訂閱它。 – 2012-04-04 22:36:40