启动新线程后UI会阻塞
本文关键字:UI 新线程 线程 启动 | 更新日期: 2023-09-27 17:57:41
单击按钮时,我将启动一个新线程(在画布上绘制省略号),但在此之后,所有窗口和按钮都被锁定。我看过这个网站上的模拟线程,但它没有帮助(对不起我的英语)
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();
}
}
}
您的新线程正在获取UI线程,并以最快的速度添加许多新的elipse。在此期间,UI线程几乎无能为力。无论如何,在while循环的大约65k次迭代后,您的程序将崩溃,因为您正抓住画笔,而窗口没有足够的资源来容纳超过65k个画笔句柄。
不管你想做什么,这都不是办法。也许你可以描述你想要实现的目标,这样我们就能真正帮助你。按照你的编码方式,我们无法使它发挥作用。