读书人

WPF线程处置模型

发布时间: 2012-09-03 09:48:39 作者: rapoo

WPF线程处理模型

?

WPF线程处置模型概述和调度程序

WPF线程处置模型操作中的线程:示例


具有长时间运行计算的单线程应用程序

“Start”(开始)按钮时,搜索开始。?

XAML

<Window x:Class="SDKSamples.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">Biggest Prime Found:</TextBlock>    <TextBlock Name="bigPrime" Margin="4,5,0,0">3</TextBlock>  </StackPanel></Window>
XAML
<Window x:Class="SDKSamples.MainWindow"    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">Biggest Prime Found:</TextBlock>        <TextBlock Name="bigPrime" Margin="4,5,0,0">3</TextBlock>    </StackPanel></Window>

VB

Imports SystemImports System.WindowsImports System.Windows.ControlsImports System.Windows.ThreadingImports System.ThreadingNamespace SDKSamples    Partial Public Class MainWindow        Inherits Window        Public Delegate Sub NextPrimeDelegate()        'Current number to check         Private num As Long = 3        Private continueCalculating As Boolean = False        Public Sub New()            MyBase.New()            InitializeComponent()        End Sub        Private Sub StartOrStop(ByVal sender As Object, ByVal e As EventArgs)            If continueCalculating Then                continueCalculating = False                startStopButton.Content = "Resume"            Else                continueCalculating = True                startStopButton.Content = "Stop"                startStopButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal, New NextPrimeDelegate(AddressOf CheckNextNumber))            End If        End Sub        Public Sub CheckNextNumber()            ' Reset flag.            NotAPrime = False            For i As Long = 3 To Math.Sqrt(num)                If num Mod i = 0 Then                    ' Set not a prime flag to true.                    NotAPrime = True                    Exit For                End If            Next            ' If a prime number.            If Not NotAPrime Then                bigPrime.Text = num.ToString()            End If            num += 2            If continueCalculating Then                startStopButton.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.SystemIdle, New NextPrimeDelegate(AddressOf Me.CheckNextNumber))            End If        End Sub        Private NotAPrime As Boolean = False    End ClassEnd Namespace
C#VB
using System;using System.Windows;using System.Windows.Controls;using System.Windows.Threading;using System.Threading;namespace SDKSamples{    public partial class Window1 : Window    {        public delegate void NextPrimeDelegate();        //Current number to check         private long num = 3;           private bool continueCalculating = false;        public Window1() : base()        {            InitializeComponent();        }        private 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()        {            // Reset flag.            NotAPrime = false;            for (long i = 3; i <= Math.Sqrt(num); i++)            {                if (num % i == 0)                {                    // Set not a prime flag to true.                    NotAPrime = true;                    break;                }            }            // If a prime number.            if (!NotAPrime)            {                bigPrime.Text = num.ToString();            }            num += 2;            if (continueCalculating)            {                startStopButton.Dispatcher.BeginInvoke(                    System.Windows.Threading.DispatcherPriority.SystemIdle,                     new NextPrimeDelegate(this.CheckNextNumber));            }        }        private bool NotAPrime = false;    }}

VB

Private Sub StartOrStop(ByVal sender As Object, ByVal e As EventArgs)    If continueCalculating Then        continueCalculating = False        startStopButton.Content = "Resume"    Else        continueCalculating = True        startStopButton.Content = "Stop"        startStopButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal, New NextPrimeDelegate(AddressOf CheckNextNumber))    End IfEnd Sub
C#VB
private 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));    }}

VB

Public Sub CheckNextNumber()    ' Reset flag.    NotAPrime = False    For i As Long = 3 To Math.Sqrt(num)        If num Mod i = 0 Then            ' Set not a prime flag to true.            NotAPrime = True            Exit For        End If    Next    ' If a prime number.    If Not NotAPrime Then        bigPrime.Text = num.ToString()    End If    num += 2    If continueCalculating Then        startStopButton.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.SystemIdle, New NextPrimeDelegate(AddressOf Me.CheckNextNumber))    End IfEnd SubPrivate NotAPrime As Boolean = False
C#VB
public void CheckNextNumber(){    // Reset flag.    NotAPrime = false;    for (long i = 3; i <= Math.Sqrt(num); i++)    {        if (num % i == 0)        {            // Set not a prime flag to true.            NotAPrime = true;            break;        }    }    // If a prime number.    if (!NotAPrime)    {        bigPrime.Text = num.ToString();    }    num += 2;    if (continueCalculating)    {        startStopButton.Dispatcher.BeginInvoke(            System.Windows.Threading.DispatcherPriority.SystemIdle,             new NextPrimeDelegate(this.CheckNextNumber));    }}private bool NotAPrime = false;

bigPrimeTextBlock?来反映搜索结果。?用后台线程处理阻止操作C#VB

using System;using System.Windows;using System.Windows.Controls;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Media.Imaging;using System.Windows.Shapes;using System.Windows.Threading;using System.Threading;namespace SDKSamples{    public partial class Window1 : Window    {        // Delegates to be used in placking jobs onto the Dispatcher.        private delegate void NoArgDelegate();        private delegate void OneArgDelegate(String arg);        // Storyboards for the animations.        private Storyboard showClockFaceStoryboard;        private Storyboard hideClockFaceStoryboard;        private Storyboard showWeatherImageStoryboard;        private Storyboard hideWeatherImageStoryboard;        public Window1(): base()        {            InitializeComponent();        }          private void Window_Loaded(object sender, RoutedEventArgs e)        {            // Load the storyboard resources.            showClockFaceStoryboard =                 (Storyboard)this.Resources["ShowClockFaceStoryboard"];            hideClockFaceStoryboard =                 (Storyboard)this.Resources["HideClockFaceStoryboard"];            showWeatherImageStoryboard =                 (Storyboard)this.Resources["ShowWeatherImageStoryboard"];            hideWeatherImageStoryboard =                 (Storyboard)this.Resources["HideWeatherImageStoryboard"];           }        private void ForecastButtonHandler(object sender, RoutedEventArgs e)        {            // Change the status image and start the rotation animation.            fetchButton.IsEnabled = false;            fetchButton.Content = "Contacting Server";            weatherText.Text = "";            hideWeatherImageStoryboard.Begin(this);            // Start fetching the weather forecast asynchronously.            NoArgDelegate fetcher = new NoArgDelegate(                this.FetchWeatherFromServer);            fetcher.BeginInvoke(null, null);        }        private void FetchWeatherFromServer()        {            // Simulate the delay from network access.            Thread.Sleep(4000);                          // Tried and true method for weather forecasting - random numbers.            Random rand = new Random();            String weather;            if (rand.Next(2) == 0)            {                weather = "rainy";            }            else            {                weather = "sunny";            }            // Schedule the update function in the UI thread.            tomorrowsWeather.Dispatcher.BeginInvoke(                System.Windows.Threading.DispatcherPriority.Normal,                new OneArgDelegate(UpdateUserInterface),                 weather);        }        private void UpdateUserInterface(String weather)        {                //Set the weather image            if (weather == "sunny")            {                       weatherIndicatorImage.Source = (ImageSource)this.Resources[                    "SunnyImageSource"];            }            else if (weather == "rainy")            {                weatherIndicatorImage.Source = (ImageSource)this.Resources[                    "RainingImageSource"];            }            //Stop clock animation            showClockFaceStoryboard.Stop(this);            hideClockFaceStoryboard.Begin(this);            //Update UI text            fetchButton.IsEnabled = true;            fetchButton.Content = "Fetch Forecast";            weatherText.Text = weather;             }        private void HideClockFaceStoryboard_Completed(object sender,            EventArgs args)        {                     showWeatherImageStoryboard.Begin(this);        }        private void HideWeatherImageStoryboard_Completed(object sender,            EventArgs args)        {                       showClockFaceStoryboard.Begin(this, true);        }            }}

C#VB

private void ForecastButtonHandler(object sender, RoutedEventArgs e){    // Change the status image and start the rotation animation.    fetchButton.IsEnabled = false;    fetchButton.Content = "Contacting Server";    weatherText.Text = "";    hideWeatherImageStoryboard.Begin(this);    // Start fetching the weather forecast asynchronously.    NoArgDelegate fetcher = new NoArgDelegate(        this.FetchWeatherFromServer);    fetcher.BeginInvoke(null, null);}

FetchWeatherFromServer?方法,然后返回,这样?Dispatcher?就可以在我们等待收集天气预报时处理事件。

读书人网 >编程

热点推荐