异步编程练习
通过本实验,熟悉和掌握任务的定义、创建和执行,以及任务的取消和状态获取。
1、创建一个WPF应用程序项目
2、将App.xaml中的Application.Resources节内容改为
3、修改MainWindow.xaml及代码隐藏类
MainWindow.xaml
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
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
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);
}
}
}
Page4.xml
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
{
/// <summary>
/// Page4.xaml 的交互逻辑
/// </summary>
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任务被取消";
}
}
}
}
运行结果
通过本实验,熟悉和掌握任务的定义、创建和执行,以及任务的取消和状态获取