线程不会同时启动

时间:2014-12-13 17:35:43

标签: c# multithreading

这里我有一个更新画布背景和元素的类我希望与元素分开进行背景更新,因为元素更新需要相当多但是当我使用线程时我没有注意到任何差异,当我暂停时其中一个都暂停了所以我猜两个都在同一个线程这里是代码

namespace 
{
    class CanvasHandler
    {
        private Canvas _canvas;
        private Grid gird;
        private Brush _image;
        private UiHandler uiHandler;
        private Thread thread,thread1;
        public CanvasHandler(Canvas canvas, UiHandler uiHandler)
        {
            this._canvas = canvas;
            this.uiHandler = uiHandler;
            this.gird = this._canvas.Parent as Grid;
        }

        public void Update()
        {

            thread = new Thread(UpdateImage);
            thread.Start();
            thread1 = new Thread(UpdateCanvas);
            thread1.Start();



        }

        public void UpdateImage()
        {
            this._canvas.Dispatcher.BeginInvoke((Action)(() => this._canvas.Background = uiHandler.SourceCanvas.Background));

        }

        public void UpdateCanvas()
        {
            this._canvas.Dispatcher.BeginInvoke((Action)(UpdateCanvas_));


        }

        private void UpdateCanvas_()
        {
            Thread.Sleep(500);
            this._canvas.Children.Clear();
            foreach (UIElement child in uiHandler.SourceCanvas.Children)
            {
                var clone = Clone(child);
                this._canvas.Children.Add(clone);


            }
        }

        public T Clone<T>(T source)
        {
            string objXaml = XamlWriter.Save(source);
            var stringReader = new StringReader(objXaml);
            XmlReader xmlReader = XmlReader.Create(stringReader);
            var t = (T)XamlReader.Load(xmlReader);
            return t;
        }

    }
}

1 个答案:

答案 0 :(得分:3)

你在这里不是多线程的。这两个函数都在Dispatcher线程中执行。

你多线程的是调用Dispatcher来处理这些函数,因为BeginInvoke调用是异步的,所以没用。

您应该做的是在线程中完成所有工作(克隆功能),然后根据它更新UI。调度员线程不应该像你正在做的那样做出繁重的工作。