alx
alx

Reputation: 61

UI blocks after starting a new thread

I'm starting a new thread (drawing ellipses on canvas) on button click, but after that all Window and buttons are locked. I've looked through simular threads on this site but it did't help (sorry for my english)

using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using Xceed.Wpf.Toolkit;

namespace WpfПотоки
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //PriorityCombo.Items.Add(1);
            //PriorityCombo.Items.Add(2);
            //PriorityCombo.Items.Add(3);
            //PriorityCombo.Items.Add(4);
            //PriorityCombo.SelectedIndex = 3;

            PriorityCombo.Items.Add(ThreadPriority.Highest);
            PriorityCombo.Items.Add(ThreadPriority.AboveNormal);
            PriorityCombo.Items.Add(ThreadPriority.Normal);
            PriorityCombo.Items.Add(ThreadPriority.BelowNormal);
            PriorityCombo.Items.Add(ThreadPriority.Lowest);
            PriorityCombo.SelectedIndex = 2;
        }

        public void Circle()
        {
            var rand = new Random();
            while (true)
            {
                this.Dispatcher.Invoke(() =>
                {
                    var e = new Ellipse();
                    e.Height = 25;
                    e.Width = 25;
                    var brush = new SolidColorBrush(ColorPicker.SelectedColor);

                    var y = rand.Next(25, (int)(Canvas1.ActualHeight - 28));
                    var x = rand.Next(25, (int)(Canvas1.ActualWidth - 28));

                    Canvas.SetTop(e, y);
                    Canvas.SetLeft(e, x);
                    e.Fill = brush;
                    Canvas1.Children.Add(e);
                });
            }            
        }


        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var thread=new Thread(Circle);
            thread.Priority = (ThreadPriority)PriorityCombo.SelectionBoxItem;
            thread.IsBackground = true;
            thread.Start();

        }

    }
}

Upvotes: 0

Views: 72

Answers (1)

nvoigt
nvoigt

Reputation: 77354

Your new thread is grabbing the UI thread and adding many new elipses as fast as it gets. There is little the UI thread could do in the meantime. Your program will crash after about 65k iterations of your while loop anyway, because you are holding onto the brushes and windows does not have enough resources to hold more than 65k handles to brushes.

Whatever you want to do, this is not the way. Maybe you can describe what you want to achieve, so we can actually help you. The way you coded it, there is nothing we can do to make it work.

Upvotes: 1

Related Questions