Onchanged c#附加表格

时间:2015-07-08 11:07:07

标签: c# multithreading textbox

每次c#中的日志文本文件发生更改时,我都会尝试附加文本框。

下面是我的代码,但我似乎无法做到。它告诉我从另一个线程c#

访问主窗体中的文本框组件
public Form1()
{

    InitializeComponent();

    string currentPath = System.Environment.CurrentDirectory;


    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = currentPath;
    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
    watcher.Filter = "*.*";
    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.EnableRaisingEvents = true;






}

private void OnChanged(object source, FileSystemEventArgs e)
{
    textBox1.AppendText("hello ah");
}

1 个答案:

答案 0 :(得分:0)

FileSystemWatcher在不同的线程上传递事件,您必须将AppendText调用编组到UI调度程序:

textBox1.Dispatcher.BeginInvoke(new Action(() =>
      {
          textBox1.AppendText("hello ah");
      }));