内容说明:视频教程总结
代码平台:visual? studio? 2019
一、MainWindow.xaml
<Window x:Class="test.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:test"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="377,165,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown"/>
<TextBox x:Name="value" HorizontalAlignment="Left" Height="23" Margin="138,211,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
</Grid>
</Window>
二、MainWindow.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
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 test
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
//添加async,使点击事件支持异步
private async void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
await Task.Run(Download);//异步执行耗时操作函数
}
private void Download()//耗时操作
{
for (int i = 0;i< 1000000000;i++)
{
int a = 3;
int b = 4;
int c = a + b;
int d = a + b + c;
int e = a + b + c + d;
}
}
}
}
1.点击事件添加async
2.await Task.Run(函数);//异步执行耗时操作函数
3.编写耗时操作的函数
说明:如果耗时操作中涉及到UI界面的更新,可以结合MVVM框架实现;
|