Unblock Thread with Dispatcher.BeginInvoke : Dispatcher « Windows Presentation Foundation « C# / CSharp Tutorial






<Window x:Class="WPFThreading.UnblockThread"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="UI Thread Blocker" Height="275" Width="225">
    <StackPanel>
      <Button Name="button1" Click="button1_click">Go to sleep</Button>
      <Button Name="button2" Click="button2_click">Try Me</Button>
      <TextBox Name="textbox1"/>
      <Label Name="UIThreadLabel"></Label>
      <Label Name="BackgroundThreadLabel"></Label>
    </StackPanel>
</Window>
//File:Window.xaml.cs

using System.Windows;
using System.Windows.Threading;
using System.Threading;

namespace WPFThreading
{
  public partial class UnblockThread : System.Windows.Window
  {
    private delegate void SimpleDelegate();
    public UnblockThread()
    {
      InitializeComponent();

      this.UIThreadLabel.Content = this.Dispatcher.Thread.ManagedThreadId;
      this.BackgroundThreadLabel.Content = "N/A";
    }

    private void LongRunningProcess() 
    {
      SimpleDelegate del1 = delegate(){ this.BackgroundThreadLabel.Content = Thread.CurrentThread.ManagedThreadId; };
      this.Dispatcher.BeginInvoke(DispatcherPriority.Send, del1);

      Thread.Sleep(5000);

      SimpleDelegate del2 = delegate() {this.textbox1.Text = "Done Sleeping...";};
      this.Dispatcher.BeginInvoke(DispatcherPriority.Send, del2);
    }

    private void button1_click(object sender, RoutedEventArgs e)
    {
      SimpleDelegate del = new SimpleDelegate(LongRunningProcess);
      del.BeginInvoke(null, null);
    }

    private void button2_click(object sender, RoutedEventArgs e)
    {
      this.textbox1.Text = "Hello WPF";
    }

  }
}
WPF Unblock Thread With Dispatcher Begin Invoke








24.124.Dispatcher
24.124.1.Unblock Thread with Dispatcher.BeginInvokeUnblock Thread with Dispatcher.BeginInvoke
24.124.2.DispatcherTimer and EventHandlerDispatcherTimer and EventHandler
24.124.3.Dispatcher.BeginInvoke with DispatcherPriority.NormalDispatcher.BeginInvoke with DispatcherPriority.Normal
24.124.4.Use DispatcherTimer to change Dependency PropertyUse DispatcherTimer to change Dependency Property
24.124.5.Dispatcher ExamplesDispatcher Examples
24.124.6.Using a DispatcherTimerUsing a DispatcherTimer
24.124.7.MailDispatcher and NotifyIconMailDispatcher and NotifyIcon
24.124.8.Using DispatcherTimer to trigger event