Jens Willmer

Tutorials, projects, dissertations and more..

Threading in C# und WPF

Anbei der Code womit sich neue WPF-Fenster in einem eigenen Thread öffnen lassen. War eine unsere Aufgaben in der Vorlesung Betriebssysteme.

MainWindow.xaml.cs

...
..
using System.Threading;

namespace Threading
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Thread thread = Thread.CurrentThread;
            this.DataContext = new
            {
                ThreadId = thread.ManagedThreadId
            };
        }

        private void OnCreateNewWindow( object sender, RoutedEventArgs e)
        {
            Thread thread = new Thread(() =>
            {
                MainWindow w = new MainWindow();
                w.Show();

                System.Windows.Threading.Dispatcher.Run();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
    }
}

MainWindow.xaml

<Window x:Class="Threading.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="132" Width="210">
    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Thread's ID is "/>
            <TextBlock Text="{Binding ThreadId}"/>
        </StackPanel>
        <Button Click="OnCreateNewWindow" Content="Create new Window" />
    </StackPanel>
</Window>