0

我正在尝试将控制台输出重定向到列表框,但是当我从另一个线程将文本写入控制台时,它会引发 InvalidOperationException

列表框编写器:

    public class ListBoxWriter : TextWriter
    {
        private ListBox list;
        private StringBuilder content = new StringBuilder();

        public ListBoxWriter(ListBox list)
        {
            this.list = list;
        }

        public override void Write(char value)
        {
            base.Write(value);
            content.Append(value);
            if (value == '\n')
            {   
                list.Items.Add(content.ToString());
                content = new StringBuilder();
            }
        }

        public override Encoding Encoding
        {
            get { return System.Text.Encoding.UTF8; }
        }
    }
4

1 回答 1

1

您正在从另一个线程访问 UI,这意味着您在将项目添加到列表时必须使用调度程序。

public class ListBoxWriter : TextWriter
    {
        private ListBox list;
        private StringBuilder content = new StringBuilder();

        public ListBoxWriter(ListBox list)
        {
            this.list = list;
        }

        public override void Write(char value)
        {
            base.Write(value);
            content.Append(value);
            if (value == '\n')
            {
                list.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => list.Items.Add(content.ToString())));                    
                content = new StringBuilder();
            }
        }

        public override Encoding Encoding
        {
            get { return System.Text.Encoding.UTF8; }
        }
    }
于 2013-09-05T13:39:22.243 回答