Search This Blog

Thursday, November 12, 2009

BackgroundWorker的用法

在WPF中,使用BackgroundWorker可以将繁重的工作放到后台。

源代码如下:

XAML:

<Window x:Class="BackgroundWorkerTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Button Margin="78,110,77,114" Name="button1" Click="button1_Click">Do Work</Button>
        <CheckBox Height="16" Margin="81,88,77,0" Name="checkBox1" VerticalAlignment="Top">Do work background</CheckBox>
        <TextBox Height="23" Margin="81,0,77,85" Name="textBox1" VerticalAlignment="Bottom" />
    </Grid>
</Window>

 

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BackgroundWorkerTest
{
    /// <summary>
    /// Window1.xaml の相互作用ロジック
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.textBox1.Text = "";
            if (checkBox1.IsChecked == true)
            {
                System.ComponentModel.BackgroundWorker myWorker = new System.ComponentModel.BackgroundWorker();
                myWorker.DoWork += myWorker_DoWork;
                myWorker.RunWorkerCompleted += myWorker_RunWorkerCompleted;
                myWorker.RunWorkerAsync();
            }
            else {
                heavyJob();
                this.textBox1.Text = "job is done";
            }
        }

        private void heavyJob() {
            Int64 number = 1000000000;
            Int64 temp = 0;
            for (int cnt = 1; cnt < number; cnt++) {
                if ((cnt % 2) == 0)
                {
                    temp /= cnt;
                }
                else {
                    temp *= cnt;
                }
            }

        }

        private void myWorker_DoWork(Object sender, System.ComponentModel.DoWorkEventArgs e) {
            heavyJob();
        }

        private void myWorker_RunWorkerCompleted(Object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) {

            this.textBox1.Text = "job is done";
        }
    }
}

No comments:

Post a Comment