2016-01-15 21 views
0

我正在構建一個程序,該程序應該觀察某個項目文件夾以更改源代碼,然後在某處並在此過程中發送這些更改,並記錄在Windows窗體文本框中更改過的文件。FileSystemWatcher - UI中的日誌結果

的代碼看起來是這樣的:

void Form_Load(object sender, EventArgs e) 
{ 
    FileSystemWatcher fsw = new FileSystemWatcher("C:\\test"); 
    fsw.Created += File_Created; 
} 

void File_Created(object sender, FileSystemEventArgs e) 
{ 
    string name = Path.GetFileName(e.FullPath); 
    logs.Text += name + Environment.NewLine; 
} 

當然,這並不是實際的代碼,但它足以看到這一點。 每次觸發File_Created事件時,它都會創建一個新線程,因此我無法從該事件與UI進行交互,它會拋出異常。

我的程序中的其他一切工作除了日誌記錄部分,但它有點煩人。

有沒有辦法解決它?

感謝, 阿里克

+1

的可能的複製[如何更新來自C#中另一個線程的GUI?](http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c) – user700390

+1

使用Invoke/BeginInvoke。嘗試搜索,因爲這已被詢問並多次回答。 – user700390

回答

1

如果您想更新從其他線程的UI,你需要使用:

Dispatcher.Invoke(new Action(() => 
{ 
    logs.Text += name + Environment.NewLine; 
})); 

我希望這可以幫助你

+0

它的工作原理!謝謝。 – areller