Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the main thread and the UI thread same in C# WPF application?

Tags:

c#

.net

wpf

Can you start the UI from another thread rather than in main thread? So heavy processing in the main thread would not block the UI is that possible?

C# 4.5 WPF application

like image 653
MonsterMMORPG Avatar asked Apr 20 '16 22:04

MonsterMMORPG


1 Answers

Yes they are the same thread. You would want to spawn off a new thread to handle major processing.

The following example simply has a button that will sleep (for 10 seconds) the main thread, once the Button_Click is called and the "sleeping" begins the whole UI becomes unresponsive.

Hope that helps.

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

Edits include grammar correction and explanation of sample/example code.

like image 126
Tyler Avatar answered Oct 28 '22 14:10

Tyler