61.异步编程1 C#例子 WPF例子

和普通的任务绑定不太相同的部分如下:

cs 复制代码
 public MainWindowViewModel()
 {
     FetchUserInfoCommand = new RelayCommand(async (param) => await FetchUserInfoAsync());
 }

 private async Task FetchUserInfoAsync()
 {
     // 模拟异步操作,比如网络请求
     await Task.Delay(2000); // 模拟网络延迟
     UserInfo = "用户信息:新员工,需要学会WPF的异步,并巩固之前的知识。";
 }
cs 复制代码
        public MainWindowViewModel()
        {
            FetchUserInfoCommand = new RelayCommand(param => FetchUserInfoAsync());
        }

        //private async Task FetchUserInfoAsync()
        private void FetchUserInfoAsync()
        {
            Thread.Sleep(1000);
            UserInfo = "用户信息:新员工,需要学会WPF的异步,并巩固之前的知识。";
        }

前者是异步,后者则是普通的绑定任务。在前台实现的功能完全相同。但是后者却会导致前台卡死。

后台代码:

cs 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace 异步
{
    public class MainWindowViewModel : INotifyPropertyChanged
    {
        private string _userInfo;
        public string UserInfo
        {
            get { return _userInfo; }
            set
            {
                _userInfo = value;
                OnPropertyChanged(nameof(UserInfo));
            }
        }


        public ICommand FetchUserInfoCommand { get; }

        //public MainWindowViewModel()
        //{
        //    //FetchUserInfoCommand = new RelayCommand(async (param) => await FetchUserInfoAsync());

        //    FetchUserInfoCommand = new RelayCommand(param => FetchUserInfoAsync());
        //}

        private async Task FetchUserInfoAsync()
        //private void FetchUserInfoAsync()
        //{
        //    // 模拟异步操作,比如网络请求
        //    //await Task.Delay(2000); // 模拟网络延迟
        //    Thread.Sleep(1000);
        //    UserInfo = "用户信息:新员工,需要学会WPF的异步,并巩固之前的知识。";
        //}

        public MainWindowViewModel()
        {
            FetchUserInfoCommand = new RelayCommand(async (param) => await FetchUserInfoAsync());
        }

        private async Task FetchUserInfoAsync()
        {
            // 模拟异步操作,比如网络请求
            await Task.Delay(2000); // 模拟网络延迟
            UserInfo = "用户信息:新员工,需要学会WPF的异步,并巩固之前的知识。";
        }




        //固定
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

    }

    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        public event EventHandler CanExecuteChanged;

        public RelayCommand(Action<object> execute) => _execute = execute;

        public bool CanExecute(object parameter) => true; // 总是可执行(简化)
        public void Execute(object parameter) => _execute(parameter);
    }
}
cs 复制代码
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 异步
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext=new MainWindowViewModel();
        }
    }
}

前台:

XML 复制代码
<Window x:Class="异步.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:异步"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <Button Content="获取用户信息" Command="{Binding FetchUserInfoCommand}" Margin="10"/>
            <TextBox Text="{Binding UserInfo, UpdateSourceTrigger=PropertyChanged}" Margin="10,20,10,10" TextWrapping="Wrap" Height="100"/>
        </StackPanel>
    </Grid>
</Window>
相关推荐
~plus~4 分钟前
.NET 8 C# 委托与事件实战教程
网络·c#·.net·.net 8·委托与事件·c#进阶
‎ദ്ദിᵔ.˛.ᵔ₎18 分钟前
模板template
开发语言·c++
大邳草民18 分钟前
Python 中 global 与 nonlocal 的语义与机制
开发语言·笔记·python
charlie11451419124 分钟前
通用GUI编程技术——图形渲染实战(二十九)——Direct2D架构与资源体系:GPU加速2D渲染入门
开发语言·c++·学习·架构·图形渲染·win32
历程里程碑29 分钟前
二叉树---二叉树的中序遍历
java·大数据·开发语言·elasticsearch·链表·搜索引擎·lua
无限进步_1 小时前
【C++】验证回文字符串:高效算法详解与优化
java·开发语言·c++·git·算法·github·visual studio
浅时光_c1 小时前
12 指针
c语言·开发语言
charlie1145141911 小时前
嵌入式现代C++工程实践——第10篇:HAL_GPIO_Init —— 把引脚配置告诉芯片的仪式
开发语言·c++·stm32·单片机·c
beyond谚语1 小时前
接口&抽象类
c#·接口隔离原则·抽象类
call me by ur name1 小时前
ERNIE 5.0 Technical Report论文解读
android·开发语言·人工智能·机器学习·ai·kotlin