Keep the UI from becoming non-responsive in single threaded application which performs a long operation. : Thread « Windows Presentation Foundation « C# / C Sharp






Keep the UI from becoming non-responsive in single threaded application which performs a long operation.

Keep the UI from becoming non-responsive in single threaded application which performs a long operation.
  

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Prime Numbers" Width="260" Height="75">
  <StackPanel Orientation="Horizontal" VerticalAlignment="Center" >
    <Button Content="Start" Click="StartOrStop" Name="startStopButton" Margin="5,0,5,0"/>
    <TextBlock Margin="10,5,0,0">Number:</TextBlock>
    <TextBlock Name="numberTextBlock" Margin="4,5,0,0">3</TextBlock>
  </StackPanel>
</Window>
//File:Window.xaml.cs

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

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public delegate void NextPrimeDelegate();
        private long num = 1;   

        private bool continueCalculating = false;

        public Window1() : base()
        {
            InitializeComponent();
        }
        public void StartOrStop(object sender, EventArgs e)
        {
            if (continueCalculating)
            {
                continueCalculating = false;
                startStopButton.Content = "Resume";
            }
            else
            {
                continueCalculating = true;
                startStopButton.Content = "Stop";
                startStopButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal,new NextPrimeDelegate(CheckNextNumber));
            }
        }
        public void CheckNextNumber()
        {
            numberTextBlock.Text = num.ToString();
            num += 2;
            if (continueCalculating)
            {
                startStopButton.Dispatcher.BeginInvoke(
                    System.Windows.Threading.DispatcherPriority.SystemIdle, 
                    new NextPrimeDelegate(this.CheckNextNumber));
            }
        }
    }
}

   
    
  








Related examples in the same category

1.WPF ThreadingWPF Threading
2.Thread Sleep in Button Click handlerThread Sleep in Button Click handler
3.Check Whether You Are Running on the UI ThreadCheck Whether You Are Running on the UI Thread
4.Ensure That You Are Running on the UI ThreadEnsure That You Are Running on the UI Thread
5.Execute a Method Asynchronously Using the Dispatcher QueueExecute a Method Asynchronously Using the Dispatcher Queue
6.ThreadPool.QueueUserWorkItemThreadPool.QueueUserWorkItem
7.BlockThread.xamlBlockThread.xaml
8.Create a multi threaded web browsing application.