[英]How to call a function that loads UI elements to different stackpanel from the main thread in WPF C# application
[英]Are the main thread and the UI thread same in C# WPF application?
您可以从另一个线程而不是主线程启动 UI 吗? 主线程中的繁重处理不会阻塞 UI 可能吗?
C# 4.5 WPF 应用程序
是的,它们是同一个线程。 您可能希望产生一个新线程来处理主要处理。
下面的示例只有一个按钮,它将使主线程休眠(10 秒),一旦调用 Button_Click 并且“休眠”开始,整个 UI 就会变得无响应。
希望有帮助。
.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="231,142,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
。CS
using System.Threading;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Thread.Sleep(10000);
}
}
}
编辑包括语法更正和示例/示例代码的解释。
我们在其上调用Application.Run
(或您启动 WPF 的任何机制)的线程是 UI 线程。 通常,这是您的应用程序启动的线程。
如果您想在不阻塞 UI 线程的情况下进行大量处理,则应该在新线程中进行。 下面是一个例子:
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
await Task.Run(() => Thread.Sleep(1000)); //Assume Thread.Sleep is your heavy processing
}
这取决于你所说的主线程是什么意思。 如果您的意思是运行Main()
的线程,那么这是可能的。 您只需要生成它,使其成为 STA 并像在Main()
所做的那样调用Application.Run()
Main()
。
此外,WPF 可以有多个 UI 线程,从而有多个调度程序。 每个 UI 线程只能访问从当前线程创建的元素(并使用当前线程的调度程序)。
如果您想避免阻塞 UI 线程,则情况并非如此,请考虑改用async\\await
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.