Amgad Serry
Amgad Serry

Reputation: 1625

threads don't start concurrently

here i have a class that updates a canvas background and elements i want to make the background update separately from the elements since the elements update takes quite a bit but when i used threading i didn't notice any difference and when i paused one of them both of them got paused so i guess both are on the same thread here is the code

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;
        }

    }
}

Upvotes: 0

Views: 76

Answers (1)

nkoniishvt
nkoniishvt

Reputation: 2521

You aren't multithreading here. Both function are executed in the Dispatcher thread.

What you've multithreaded is the call to the Dispatcher to handle those functions, which is not useful as BeginInvoke call is asynchronous.

What you should do is make all the work (the Clone function) in a thread and then update UI according to it. The dispatcher thread shouldn't ever make heavy works like what you're doing.

Upvotes: 3

Related Questions