c# 进程与线程,抽奖程序
一、进程:
static void Main(string[] args)
{
//process中的静态方法,类型名.方法名
//显示所有进程
Process[] pross = Process.GetProcesses();
foreach (var item in pross)
{
Console.WriteLine(item);
//结束所有进程
// item.Kill();
}
//打开程序
Process.Start("calc"); //打开计算器
Process.Start("explorer", "d:");//打开D盘
Process.Start("iexplore", "http://www.baidu.com"); //打开浏览器
//打开指定文件
Process pro = new Process(); //1.创建进程
//2.指定启动参数
ProcessStartInfo psinfo = new ProcessStartInfo("d:\\1.exe");
pro.StartInfo = psinfo;
pro.Start();
}
二、线程:

1.线程调用的冲突解决:
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false; //在构造函数或form_load中添加这一句
}


private void button1_Click(object sender, EventArgs e)
{
Thread th = new Thread(Methods); //传入方法参数
th.Start(); //标记线程准备好,由cpu决定执行时间
//将线程设置为后台线程,这样前台界面关闭,所有后台线程就关闭了
th.IsBackground =true;
}
public void Methods()
{
MessageBox.Show("dddd");
}
2.主窗体关闭,线程仍有可能访问主窗体资源,进而报错,所以关闭时强制检查
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//关闭窗体时,如果线程仍在运行,强制关闭
if (th!=null)
{
th.Abort();//线程被关闭后不能重新调用,报错
}
}
总结:注意两个容易报异常的点:
<1>. 主线程关闭,后台仍运行-------------将运行的线程设置为后台进程,界面关闭即停止
<2>. 关闭程序报错-----------------------关闭时强制检查运行的进程状态
3.线程的静态方法:
thread.sleep(1)
4.线程传递带参数的方法:
private void button3_Click(object sender, EventArgs e)
{
Thread th = new Thread(Test); //这里的方法必须是不带参数的void
th.Start("123"); //传入的参数放到start
}
public void Test(object a) //方法参数必须是object类型
{
s=(string)a; // 强转换成字符串
}
练习1:抽奖程序
原理: 程序分线程执行随机数,主线程控制停止开始

public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void uiButton1_Click(object sender, EventArgs e)
{
Thread th = new Thread(PlayGame); //拿到外面
if (judge==false)
{
judge = true;
th.IsBackground = true; //后台进程
th.Start();
uiButton1.Text = "停止";
}
else
{
judge = false;
th.Abort();
uiButton1.Text = "开始";
}
}
bool judge=false;
public void PlayGame()
{
while (judge)
{
Random r = new Random();
uiLabel1.Text= r.Next(0, 10).ToString();
uiLabel2.Text = r.Next(0, 10).ToString();
uiLabel3.Text = r.Next(0, 10).ToString();
}
}

浙公网安备 33010602011771号