C# 多執行緒

iamzxf發表於2015-05-09

開啟和關閉多執行緒,例程如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Text;

namespace calcDemo
{
    class ProcessDemo
    {
        public void startProcess(int n)
        {
            Process p;
            for (int i = 0; i < n; i++)
            {
                p = Process.Start("calc.exe");
                Console.WriteLine("已經執行{0}個程式",i+1);
            }
        }

        public void exitProcess()
        {
            Process[] ps = Process.GetProcessesByName("calc");
            foreach (Process p in ps)
            {
                Console.WriteLine("回車殺死一個程式");
                Console.ReadLine();
                p.Kill();
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ProcessDemo pd = new ProcessDemo();
            pd.startProcess(3); 
            pd.exitProcess();
        }
    }
}

類似,也可以將這種思想用在其他程式,例如,mspaint(畫圖),我們將相關程式碼用在windows窗體設計,如下:

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

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Process.Start("mspaint.exe");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Process[] mspaintProcess = Process.GetProcessesByName("mspaint");
            foreach (Process p in mspaintProcess)
                p.CloseMainWindow();
        }
    }
}

kill是強制終止,CloseMainWindow是請求終止,但不強求應用程式退出。


相關文章