当前位置 博文首页 > 文章内容

    在c#中使用异步等待构建响应式UI

    作者: 栏目:未分类 时间:2020-08-10 9:01:59

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    为什么要构建响应式UI?答案似乎很明显,最终用户应该体验到应用程序不经常挂起(对于开发人员POV,一段时间的后台操作使它看起来像挂起)。因此,让我们学习使用异步等待关键字构建响应UI Visual Studio 2012引入了一种简化的方法——异步编程,它利用了。net Framework 4.5和Windows运行时中的异步支持。编译器完成开发人员以前做的困难工作,而应用程序保留类似于同步代码的逻辑结构。这是从MSDN中提取的 源代码使用的是Visual Studio 2015 Community Edition, WPF, c#, . net 4.5,在Windows 7操作系统上。但是它可以在Windows 8和Windows 10上使用Visual Studio 2013/2012(任何版本)。 CodeProject上 在c#中使用异步等待构建响应式UI 一个简单的WPF应用程序,读取12MB的文本文件,然后循环遍历并返回唯一的单词及其在文本文件中的出现次数。我没有使用线程睡眠或HttpClient来演示异步等待,而是使用word计数之类的示例。 创建时间占用库“WordCountLib” 创建命名为“AsyncAwaitDemoApp”的空白解决方案。创建命名为“WordCountLib”的类库,并创建c#类文件“WordCountClass”。复制下面包含方法“FindWordCounts”和“FindWordCountsAsync”的代码。 , 隐藏,收缩,复制Code

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    
    namespace WordCountLib
    {
        public class WordCountClass
        {
            /// 
            /// Reads through the file, generates unique words and its number of occurrences
            /// 
            /// 
            public List FindWordCounts()
            {
                //Ensure that LongFile.txt exists
                var words = Regex.Matches(File.ReadAllText(@"D:\LongFile.txt"), @"\w+").Cast()
                .Select((m, pos) => new { Word = m.Value, Pos = pos })
                .GroupBy(s => s.Word, StringComparer.CurrentCultureIgnoreCase)
                .Select(g => new Words { WordName = g.Key, NoOfOccurance = g.Select(z => z.Pos).Count() })
                .ToList();
    
                return words;
            }
    
            /// 
            /// Reads through the file, generates unique words and its number of occurrences using Async and Await
            /// 
            /// 
            public async Task<list> FindWordCountsAsync()
            {
                //Ensure that LongFile.txt exists
                var words = Regex.Matches(File.ReadAllText(@"D:\LongFile.txt"), @"\w+").Cast()
                .Select((m, pos) => new { Word = m.Value, Pos = pos })
                .GroupBy(s => s.Word, StringComparer.CurrentCultureIgnoreCase)
                .Select(g => new Words { WordName = g.Key, NoOfOccurance = g.Select(z => z.Pos).Count() });
    
                //This is more like Task-Based Asynchronous Pattern
                return await Task.Run(() => words.ToList());           
            }
        }
    }

    , 创建c#类“Words”。这是用于保存单词名称及其出现的POCO类。复制下面的 , 隐藏,复制Code

    namespace WordCountLib
    {
        public class Words
        {
            public string WordName { get; set; }
            public int NoOfOccurance { get; set; }
        }
    }

    , txt包含从http://norvig.com/big.txt复制的文本;我已经复制了所有的文本两次,所以文件是12MB和处理应该花费时间。确保你有文件在D:\LongFile.txt或其他文件发现异常。 使用WPF构建UI 创建WPF应用程序“WordCount”。,添加" WordCountLib "程序集引用,以便我们可以调用WordCountClass方法。打开主窗口。并复制下面的代码。这是我们的WPF的启动窗口。使用工具栏绘制不是那么优雅,但那是不必要的。 , 隐藏,收缩,复制Code

    <Window
            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:WordCount.UI"
            xmlns:WordCountLib="clr-namespace:WordCountLib;assembly=WordCountLib" x:Class="WordCount.UI.MainWindow"
            mc:Ignorable="d"
            Title="Async Await Demo" Height="600" Width="825" WindowStartupLocation="CenterScreen">
        
            <button>
                    
            <label>
            
                
                    
                        
                            
                                
                                
                            
                            <label>
                            <label>
                        </label></label>
                    
                
            
            
                
                    
                        
                            
                                
                                
                            
                            <label>
                            <label>
                        </label></label>
                    
                
            
            </label></button><button>
    
        
    </button>

    , MainWindow.xaml开放。它的代码后文件,为我们的启动窗口。复制下面的代码。 方法“btndwn_Click”是旧学校的类型为“搜索词”按钮点击事件处理程序,它实例化“WordCountClass”,称“FindWordsCounts”,显示列表框和把一个单词列表绑定到列表框方法“btndwnasyn_Click”是旧学校类型的按钮点击事件处理程序为“搜索词异步方式”,它实例化“WordCountClass”,称“FindWordsCountsAsync”,显示列表框和结合单词列表框的列表。注意,它有async关键字在它的方法签名和等待关键字,而“FindWordsCountsAsync”“Log”是非常简单的方法日志信息到屏幕。 构建并运行它,在它加载屏幕后检查图像。 如果我们仔细看,await关键字是内联的,而调用“FindWordsCountsAsync”。这清楚地表明该方法是耗时的,并且会阻塞UI线程。 , 隐藏,收缩,复制Code

    using System;
    using System.Windows;
    using WordCountLib;
    
    namespace WordCount.UI
    {
        /// 
        /// Interaction logic for MainWindow.xaml
        /// 
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            /// 
            /// Button click Synchronous processing
            /// 
            
            private  void btndwn_Click(object sender, RoutedEventArgs e)
            {
                Log("START");
                
                if (listBox.Visibility == Visibility.Visible)
                {
                    listBox.Visibility = Visibility.Collapsed;
                }
    
                WordCountClass wrdSimple = new WordCountClass();            
                var listCount = wrdSimple.FindWordCounts();            
                listBox.Visibility = Visibility.Visible;
                listBoxasync.Visibility = Visibility.Collapsed;
                listBox.ItemsSource = listCount;            
                Log("Done ");
            }
            
            private async void btndwnasyn_Click(object sender, RoutedEventArgs e)
            {
                Log("START Async");
                if (listBoxasync.Visibility == Visibility.Visible)
                {
                    listBoxasync.Visibility = Visibility.Collapsed;
                }
                WordCountClass wrdSimple = new WordCountClass();
                var listCount = await wrdSimple.FindWordCountsAsync();
                listBoxasync.Visibility = Visibility.Visible;
                listBox.Visibility = Visibility.Collapsed;
                listBoxasync.ItemsSource = listCount;
                
                Log("Done Async");
            }
    
            private void Log(string text)
            {
                string line = string.Format("{0:HH:mm:ss.fff}: {1}
    \n", DateTime.Now, text); logtxtBlock.AppendText(line); } } }

    , 用于异步等待演示的WPF主窗口 , 测试WPF UI的响应性 点击按钮“搜索词”,尝试移动窗口,调整它的大小。你不能做任何事情,因为它读取文件,找到所有的字计数和绑定到列表框。这称为无响应UI或应用程序挂起。看看下面的GIF图片。注意,在它加载列表框后,屏幕窗口移动了一点,因为在按钮点击后,我试图使用窗口。 点击按钮时没有响应的UI 现在再次运行应用程序,点击“异步方式搜索单词”。只需移动窗口,调整大小,查看日志信息被写入。这叫响应式UI使用异步等待在c#只是发挥它通过点击按钮来回。 使用异步等待响应UI , 异步方法旨在是非阻塞操作。异步方法中的await表达式在等待的任务运行时不会阻塞当前线程。async和await关键字不会导致创建额外的线程。异步方法不需要多线程,因为异步方法不运行在自己的线程上。 c#中使用Async Await的post构建响应UI首先出现在Mithunvp.com上。 本文转载于:http://www.diyabc.com/frontweb/news8286.html