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>
相关推荐
2501_916007471 天前
Java界面开发工具有哪些?常用Java GUI开发工具推荐、实战经验与对比分享
android·java·开发语言·ios·小程序·uni-app·iphone
_码力全开_1 天前
Python从入门到实战 (14):工具落地:用 PyInstaller 打包 Python 脚本为可执行文件
开发语言·数据结构·python·个人开发
tpoog1 天前
[C++项目框架库]redis的简单介绍和使用
开发语言·c++·redis
yi碗汤园1 天前
【一文了解】C#的StringComparison枚举
开发语言·前端·c#
Larry_Yanan1 天前
QML学习笔记(十九)QML的附加信号处理器
开发语言·笔记·qt·学习·ui
某不知名網友1 天前
I/O 多路转接之 epoll:高并发服务器的性能利器
开发语言·php
郝学胜-神的一滴1 天前
深入理解 C++ 中的 `std::bind`:功能、用法与实践
开发语言·c++·算法·软件工程
zhangfeng11331 天前
wgcna 相关性热图中4个颜色 4个共表达模块 的模块基因是否都要做GO/KEGG分析”,核心取决于你的**研究目标和模块的生物学意义*
开发语言·r语言·生物信息
come112341 天前
Go 语言中的结构体
android·开发语言·golang
Dream_Ji1 天前
Swift 入门(一 - 基础语法)
开发语言·ios·swift