C#网络应用编程,实验七: 异步编程练习

文章目录

  • 异步编程练习
    • 1、创建一个WPF应用程序项目
    • 2、将App.xaml中的Application.Resources节内容改为
    • 3、修改MainWindow.xaml及代码隐藏类
    • MainWindow.cs主要内容
    • Page4.xml
    • Pag4.cs
    • 运行结果

异步编程练习

通过本实验,熟悉和掌握任务的定义、创建和执行,以及任务的取消和状态获取。

1、创建一个WPF应用程序项目

2、将App.xaml中的Application.Resources节内容改为

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style x:Key="LabelStyle" TargetType="Label">
            <Setter Property="FontSize" Value="14"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="Background" Value="AliceBlue"/>
        </Style>
        <Style x:Key="BorderStyle" TargetType="Border">
            <Setter Property="Height" Value="35"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Background" Value="AliceBlue"/>
        </Style>
    </Application.Resources>
</Application>

C#网络应用编程,实验七: 异步编程练习_第1张图片

3、修改MainWindow.xaml及代码隐藏类

MainWindow.xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid Margin="20">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Rectangle Grid.ColumnSpan="2" Fill="White" RadiusX="14" RadiusY="14" Stroke="Blue" StrokeDashArray="3"/>
        <Rectangle Grid.Column="0" Margin="7" Fill="#FFF0F9D8" RadiusX="10" RadiusY="10" Stroke="Blue" StrokeDashArray="3"/>
        <Rectangle Grid.Column="0" Margin=" 20" Fill="White" Stroke="Blue"/>
        <ScrollViewer Grid.Column="0" Margin="20">
            <StackPanel>
                <StackPanel.Resources>
                    <Style TargetType="Button">
                        <Setter Property="HorizontalContentAlignment" Value="Center"/>
                        <Setter Property="Margin" Value="5 10 5 0"/>
                        <Setter Property="Padding" Value=" 15 0 15 0"/>
                        <Setter Property="FontSize" Value=" 10"/>
                        <EventSetter Event="Click" Handler="button_Click"/>
                    </Style>
                </StackPanel.Resources>
                <Button Content="例1(StartStopProcess)" Tag="/Examples/Page1.xaml"/>
                
            </StackPanel>
        </ScrollViewer>
        <Frame Name="frame1" Grid.Column="1" Margin="10" BorderThickness="1" BorderBrush="Blue" NavigationUIVisibility="Hidden"/>
    </Grid>
</Window>

C#网络应用编程,实验七: 异步编程练习_第2张图片

MainWindow.cs主要内容

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApp1
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        Button oldButton = new Button();
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.Source as Button;
            btn.Foreground = Brushes.Black;
            oldButton.Foreground = Brushes.Black;
            oldButton = btn;
            frame1.Source = new Uri(btn.Tag.ToString(), UriKind.Relative);
        }
    }
}

C#网络应用编程,实验七: 异步编程练习_第3张图片

Page4.xml

<Page x:Class="WpfApp1.Examples.Page4"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:WpfApp1.Examples"
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
      Title="Page4">

    <DockPanel Background="White">
        <Border DockPanel.Dock="Top"  Style="{StaticResource BorderStyle}">
            <TextBlock Text="Task.Run方法基本用法" Style="{StaticResource TitleStyle}"></TextBlock>
        </Border>
        <Border DockPanel.Dock="Bottom" Style="{StaticResource BorderStyle}">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                
                <Button x:Name="btnStart" Width="60" 
                        Content="启动任务" Click="BtnStart_Click" Margin="0,0,0,0.2"/>
                <Button x:Name="btnStop"  Margin="20,0,0,0" Width="60"
                    Content="终止任务" Click="BtnStop_Click"/>
            </StackPanel>

            


        </Border>
        <ScrollViewer>
            <StackPanel Background="White" TextBlock.LineHeight="20">
                <TextBlock x:Name="textBlock1" Margin="0 10 0 0" TextWrapping="Wrap" />
            </StackPanel>

        </ScrollViewer>

    </DockPanel>
</Page>

Pag4.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApp1.Examples
{
    /// 
    /// Page4.xaml 的交互逻辑
    /// 
    public partial class Page4 : Page
    {
        private System.Threading.CancellationTokenSource cts;
        private MyTasks t = new MyTasks();

        public Page4()
        {
            InitializeComponent();
            MyHelps.ChangeState(btnStart, true, btnStop, false);
        }

        private  void BtnStop_Click(object sender, RoutedEventArgs e)
        {
            cts.Cancel();
            MyHelps.ChangeState(btnStart,true,btnStop,false);
        }

        private async void BtnStart_Click(object sender, RoutedEventArgs e)
        {
            MyHelps.ChangeState(btnStart, false, btnStop, true);
            cts = new System.Threading.CancellationTokenSource();
            textBlock1.Text = "开始执行任务......";
            try
            {
                await Task.Run(() => t.Method1(), cts.Token);
                textBlock1.Text += "\n任务1执行完毕";
                var sum = await Task.Run(() => t.Method2(), cts.Token);
                textBlock1.Text += "\n任务2(计算1到1000的和)结果为:"+sum;
                var a = await Task.Run(() => t.Method3(39, 8), cts.Token);
                textBlock1.Text += string.Format("\n任务3(求39除以8的商和余数)结果为:{0},{1}\n", a.Item1, a.Item2);
                while (true)
                {
                    textBlock1.Text += await Task.Run(() => t.Method1("a"),cts.Token);
                    textBlock1.Text += await Task.Run(() => t.Method1("b"),cts.Token);
                }


            }
            catch(OperationCanceledException)
            {
                textBlock1.Text += "\n任务被取消";
            }
           

        }
    }
}

运行结果

C#网络应用编程,实验七: 异步编程练习_第4张图片

C#网络应用编程,实验七: 异步编程练习_第5张图片

通过本实验,熟悉和掌握任务的定义、创建和执行,以及任务的取消和状态获取

你可能感兴趣的:(C#,c#,开发语言,wpf)