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>
相关推荐
mrbone1112 分钟前
Git-git worktree的使用
开发语言·c++·git·cmake·worktree·gitab
浪裡遊23 分钟前
Sass详解:功能特性、常用方法与最佳实践
开发语言·前端·javascript·css·vue.js·rust·sass
真实的菜30 分钟前
JVM类加载系统详解:深入理解Java类的生命周期
java·开发语言·jvm
代码讲故事1 小时前
多种方法实现golang中实现对http的响应内容生成图片
开发语言·chrome·http·golang·图片·快照·截图
虾球xz1 小时前
CppCon 2018 学习:EFFECTIVE REPLACEMENT OF DYNAMIC POLYMORPHISM WITH std::variant
开发语言·c++·学习
Allen_LVyingbo2 小时前
Python常用医疗AI库以及案例解析(2025年版、上)
开发语言·人工智能·python·学习·健康医疗
小哈龙2 小时前
裸仓库 + Git Bash 搭建 本地 Git 服务端与客户端
开发语言·git·bash
唐青枫2 小时前
C#.NET log4net 详解
c#·.net
G探险者2 小时前
《如何在 Spring 中实现 MQ 消息的自动重连:监听与发送双通道策略》
java·开发语言·rpc
weixin_437398213 小时前
转Go学习笔记
linux·服务器·开发语言·后端·架构·golang