winform 使用task不卡界面的2种方式

摘要:
//////如果应释放托管资源,则为true;否则,它为false=null)){components.Dispose();}基础处置;}#regionWindows窗体设计器生成的代码//////设计器支持的必需方法-不要修改///使用代码编辑器修改此方法的内容。

方法1:

            button1.Enabled = false;
            TaskScheduler uiContext = TaskScheduler.FromCurrentSynchronizationContext();
            Task t = Task.Factory.StartNew(async () =>
             {
                 for (int i = 0; i < 5; i++)
                 {
                     Console.WriteLine("任务1: " + DateTime.Now.ToString("ss.fff"));
                     await Task.Delay(1000);
                 }
                 return 1;
             }).ContinueWith(m =>
             {
                 button1.Enabled = true;
                 Console.WriteLine("任务1:结束");
             }, uiContext);

方法2:

            button2.Enabled = false;
            TaskScheduler ui = TaskScheduler.FromCurrentSynchronizationContext();
            Task t = Task.Factory.StartNew(async () =>
            {
                for (int i = 0; i < 5; i++)
                {
                    Console.WriteLine("任务2: " + DateTime.Now.ToString("ss.fff"));
                    await Task.Delay(1000);
                }
                return 1;
            }).ContinueWith(m =>
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    button2.Enabled = true;
                    Console.WriteLine("任务2:结束");
                }));
            });
winform 使用task不卡界面的2种方式第1张winform 使用task不卡界面的2种方式第2张
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            TaskScheduler ui = TaskScheduler.FromCurrentSynchronizationContext();
            Task t = Task.Factory.StartNew(() =>
             {
                 for (int i = 0; i < 5; i++)
                 {
                     Console.WriteLine("任务1: " + DateTime.Now.ToString("ss.fff"));
                     Task.Delay(1000).Wait();
                 }
                 return 1;
             }).ContinueWith(m =>
             {
                 button1.Enabled = true;
                 Console.WriteLine("任务1:结束");
             }, ui);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            TaskScheduler ui = TaskScheduler.FromCurrentSynchronizationContext();
            Task t = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 5; i++)
                {
                    Console.WriteLine("任务2: " + DateTime.Now.ToString("ss.fff"));
                    Task.Delay(1000).Wait();
                }
                return 1;
            }).ContinueWith(m =>
            {
                ButtonEnabled();
            });
        }

        private void ButtonEnabled()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                button2.Enabled = true;
                Console.WriteLine("任务2:结束");
            }));
        }

        private int i = 0;
        private void btnOperate_Click(object sender, EventArgs e)
        {
            lblMsg.Text = i++.ToString();
        }
    }
}
View Code
winform 使用task不卡界面的2种方式第1张winform 使用task不卡界面的2种方式第2张
namespace WindowsFormsApp1
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.btnOperate = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.lblMsg = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(161, 51);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "开始";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // btnOperate
            // 
            this.btnOperate.Location = new System.Drawing.Point(312, 62);
            this.btnOperate.Name = "btnOperate";
            this.btnOperate.Size = new System.Drawing.Size(150, 99);
            this.btnOperate.TabIndex = 0;
            this.btnOperate.Text = "点开始后,再点我不阻塞";
            this.btnOperate.UseVisualStyleBackColor = true;
            this.btnOperate.Click += new System.EventHandler(this.btnOperate_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(161, 127);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 0;
            this.button2.Text = "开始";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(91, 62);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(47, 12);
            this.label1.TabIndex = 1;
            this.label1.Text = "方法1:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(91, 132);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(47, 12);
            this.label2.TabIndex = 1;
            this.label2.Text = "方法2:";
            // 
            // lblMsg
            // 
            this.lblMsg.AutoSize = true;
            this.lblMsg.BackColor = System.Drawing.Color.Transparent;
            this.lblMsg.Font = new System.Drawing.Font("宋体", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lblMsg.ForeColor = System.Drawing.Color.Tomato;
            this.lblMsg.Location = new System.Drawing.Point(352, 26);
            this.lblMsg.Name = "lblMsg";
            this.lblMsg.Size = new System.Drawing.Size(65, 22);
            this.lblMsg.TabIndex = 1;
            this.lblMsg.Text = "-----";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(510, 254);
            this.Controls.Add(this.lblMsg);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.btnOperate);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button btnOperate;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label lblMsg;
    }
}
View Code

免责声明:文章转载自《winform 使用task不卡界面的2种方式》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Python入门篇-pyenv安装及应用原创:python的requests.post()向后端传递数据,数组结构需将python数据结果转换成JSON下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

winform中如何在TextBox中只能输入数字(可以带小数点)

可以采用像web表单验证的方式,利用textbox的TextChanged事件,每当textbox内容变化时,调用正则表达式的方法验证,用一个label在text后面提示输入错误,具体代码如下: private void textBox1_TextChanged(objectsender, EventArgs e) {...

winform 学习笔记

1、数据表格显示 2、窗体透明代码 3、用信号量实现线程的挂起和恢复 4、加载VisionPP 5、VP实现相机外部触发并注册回调 6、显示图片处理过程 7、单个窗口重复使用 8、VP保存图片 9、多线程并行处理——Task类 10、跨线程使用UI控件 11、图表显示数据 12、窗体淡入淡出显示-winform  13、基于M库访问PLC寄存器 14、串口...

Winform开发框架之介绍

框架已经正式改名为:YESWin开发框架, 最新资料请前往:YESWinform 简介 - YES快速开发平台框架 (yesdotnet.com)  winform开发框架,尽量减少程序员在界面中的代码量和工作量,Model自动生成,界面以及控件自动生成,简单的逻辑自动生成。自动生成的界面已经实现简单逻辑增删改查功能。 其他开发框架都已经或多火烧实现了这些...

WinForm利用 WinApi实现 淡入淡出 弹出 效果 仿QQ消息

消息框: using System.Runtime.InteropServices; namespace Windows_API_实现屏幕右下角_消息框_ { public partial class Msg : Form { public Msg() { InitializeCom...

C#在WinForm开发中Label换行方法

在开发WinForm中可能经常遇到Label要显示的内容太长,但却不能换行的问题。本文将为大家提供三个解决方法,供大家选择 很多朋友都会在开发WinForm中遇到Label要显示的内容太长,但却不能换行的问题.这里我总结了几种方法,供大家参考。 第一种是把Label的AutoSize属性设为False,手动修改Label的大小.这样的好处是会因...

C#winform的textbox怎么设置滚动条

用 C#开发软件的时候文本框textbox是没有滚动条的,而且是单行文本。下面教大家如何设置多行,并且设置横向滚动条和垂直滚动条。 打开VS工具,创建一个winform窗体项目。系统会自动创建一个主窗体。在左边工具栏搜索textbox后,拉到窗体里面。 这个时候你看到一个单行文本框,右击文本框,点击属性,右边会显示文本框的属性窗口。选择MutilLine...