启动新线程后的UI块

时间:2014-04-09 03:29:44

标签: c# wpf multithreading

我在点击按钮时开始一个新线程(在画布上绘制省略号),但之后所有窗口和按钮都被锁定。我已经浏览了这个网站上的类似线程,但它没有帮助(对不起我的英文)

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();

        }

    }
}

1 个答案:

答案 0 :(得分:1)

您的新主题正在抓取UI线程并尽快添加许多新的elipses。 UI线程在此期间几乎无法做到。无论如何,你的程序将在你的while循环大约65k次迭代后崩溃,因为你抓住画笔并且窗口没有足够的资源来容纳超过65k的画笔手柄。

无论你想做什么,这都不是。也许你可以描述你想要达到的目标,所以我们可以真正帮助你。你编写它的方式,我们无法做任何事情来使它工作。