WinFrom 线程的使用(开启、暂停、停止)

本文介绍如何在C#中通过两种方法创建线程,并演示了如何使用Start(), Sleep(), Abort(), Suspend() 和 Resume()等方法来管理线程。第一种方法直接在窗体类中定义并启动线程,第二种方法则通过委托和BeginInvoke实现线程的异步调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:


启用线程:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;


namespace WindowsFormsApplication1
{
    public delegate void BackGroundWorkers();


    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            
        }
Thread th;

        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            GetICount();   
        }


        int i = 0;


        public void GetICount()
        {
            i++;
            this.label1.Text = i.ToString();
            Thread.Sleep(1000);  //暂停线程
             = new Thread(new ThreadStart(GetICount));
            th.IsBackground = true;
            th.Start();
        }
    }
}


停止线程:

public void StopThread()

{

th.Abort();   //停止线程

}


方法二:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;


namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }


        private delegate void GetInfo();




        private void Form2_Load(object sender, EventArgs e)
        {
            GetTime();
        }
        
        private int i = 0;


        /// <summary>
        /// 线程执行的方法
        /// </summary>
        public void GetTime()
        {


            i++;
            this.label1.Text = i.ToString();
            Thread.Sleep(200);
            GetInfo gets = new GetInfo(GetTime);
            gets.BeginInvoke(null, null);
        }
    }
}



Start():启动线程;
Sleep(int):静态方法,暂停当前线程指定的毫秒数; 
Abort():通常使用该方法来终止一个线程;
Suspend():该方法并不终止未完成的线程,它仅仅挂起线程,以后还可恢复; 
Resume():恢复被Suspend()方法挂起的线程的执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值