进程类Process与多线程Thread

来源:互联网 发布:命令与征服 知乎 编辑:程序博客网 时间:2024/04/20 11:57

进程类(Process)的基本操作:

//通过进程类查询系统所有进程            Process[] pros = Process.GetProcesses();            foreach (var item in pros)            {                Console.WriteLine(item);            }                        //通过进程打开一些应用程序            Process.Start("calc");            Process.Start("iexplore", "http://www.baidu.com");            //通过一个进程打开指定的文件            ProcessStartInfo psi = new ProcessStartInfo(@"C:\Users\Administrator\Desktop\ado.net简单记录.txt");            Process p = new Process();            p.StartInfo=psi;            p.Start();            Console.ReadKey();

多线程:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;namespace 多线程{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        Thread th;        private void button1_Click(object sender, EventArgs e)        {            //创建一个线程,执行Test方法             th = new Thread(Test);            //将线程设置为后台线程,只要所有前台线程关闭,后台自动关闭            th.IsBackground = true;            //标记此线程可以随时被执行,具体何时,看CPU决定            th.Start();        }        public void Test()        {            for (int i = 0; i < 10000; i++)            {                //Console.WriteLine(i);                textBox1.Text = i.ToString();            }        }        private void Form1_Load(object sender, EventArgs e)        {            //取消跨线程访问的限制            Control.CheckForIllegalCrossThreadCalls = false;        }        private void Form1_FormClosing(object sender, FormClosingEventArgs e)        {            //当点击关闭窗口时,判断线程是否还在运行            if (th != null)            {                //如果在,则手动终止,注意:终止之后不能再次启动。                th.Abort();//            }        }    }}


0 0
原创粉丝点击