C# WPF 关于async/await异步用法

写数据传给前台的时候老是卡死,发现用了这个方法也不行,然后发现要再最上层套上Task.Run()才行,在此记录下。

首先把流程源码放出来 这些代码也包含了一个定时器和记录前台显示,每天几点执行一次,需要拿去,从最底层开始

<Button
                        x:Name="btnStart"
                        Width="100"
                        Height="30"
                        Margin="5"
                        HorizontalAlignment="Left"
                        Click="btnStart_Click"
                        Content="启动" />
<TextBox
                            Name="txtLog"
                            Grid.Row="1"
                            Grid.ColumnSpan="2"
                            AcceptsReturn="True"
                            Foreground="Black"
                            HorizontalScrollBarVisibility="Auto"
                            TextWrapping="Wrap"
                            VerticalScrollBarVisibility="Auto"  />

  然后到数据层

 
public async Task Execute(string[] args)
        {
            try
            {
                await Task.Run(() =>
                {
                    LoadDisplay("你迟到了");
                });
            }
            catch (Exception e)
            {
                //LoadDisplay($"请求接口时出现异常{e.Message}");
            }
        }
/// <summary>
        /// 输出日志信息
        /// </summary>
        /// <param name="news"></param>
        public void LoadDisplay(string news)
        {
            this.txtLog.Dispatcher.BeginInvoke((Action)delegate
            {
                this.txtLog.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss " + news + "\r\n"));
                if (IsVerticalScrollBarAtBottom)
                {
                    this.txtLog.ScrollToEnd();
                }
            });
        }

  调用层

/// <summary>
        /// //要执行的任务
        /// </summary>
        /// <param name="state"></param>
        private async void DoTask(object state)
        {
            string[] args = new string[0];
            //执行功能...
            await Execute(lines);
            //再次设定
            SetTaskAtFixedTime();
        }

开始new一个计时器

/// <summary>
        /// //设定定时执行
        /// </summary>
        public void SetTaskAtFixedTime()
        {
            DateTime now = DateTime.Now;
            DateTime oneOClock = DateTime.Today.AddHours(7.0); //晨7:00
            if (now > oneOClock)
            {
                oneOClock = oneOClock.AddDays(1.0);
            }
            int msUntilFour = (int)(oneOClock - now).TotalMilliseconds;
 
            var t = new System.Threading.Timer(DoTask);
            t.Change(msUntilFour, Timeout.Infinite);
        }

最后 按钮点击事件

/// <summary>
        /// 启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            System.Threading.Tasks.Task.Run(() =>
            {
                SetTaskAtFixedTime();
            });
        }

最后不用说了,反正界面绝对不会卡顿,这些也是网上凑的

posted @ 2021-11-17 18:19  FalyEnd  阅读(445)  评论(0)    收藏  举报