C#多进程并行

为了并行执行多个任务,可以启动多个进程(并行数)。

下面提供两种方法,总任务数10,最大并行数4。

一、方法1

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

namespace 进程并行
{
   public class StartProcess1
    {
        int totalProcess = 10;//总任务数
        int maxParallelProcess = 4;//并行最大进程数
        int curRunningProcess = 0;//当前运行进程数
        public void Do()
        {
            DoEvents();
        }

        /// <summary>
        /// 执行进程
        /// </summary>
        private  void DoEvents()
        {
            for (int i = 0; i < totalProcess; i++)
            {
                ProcessStartInfo processInfo = new ProcessStartInfo();
                processInfo.FileName = @"C:\进程.exe";
                processInfo.Arguments = (i + 1).ToString();
                Process pro = new Process();
                pro.EnableRaisingEvents = true;
                pro.StartInfo = processInfo;
                pro.Exited += new EventHandler(process_Exited);
                pro.Start();
                //pro.WaitForExit(18000);
                curRunningProcess++;
                //如果大于最大并行数,就等待进程退出,是并行数不超过最大并行数
                while (curRunningProcess >= maxParallelProcess)
                {
                    if (i >= totalProcess - 1)
                    { return; }
                }
            }
        }

        /// <summary>
        /// 进程结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       private void process_Exited(object sender, EventArgs e)
        {
            curRunningProcess--;
        }
    }
}

二、方法2

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

namespace 进程并行
{
   public class StartProcess2
    {
        static int totalProcess = 10;//总任务数
        static int maxParallelProcess = 4;//并行最大进程数
        static int doneProcess = 0;//已经执行完的进程数
        static int toPro = 0;//第一次启动的进程数
        public  void Do2()
        {
            //当总任务数小于进程并行数时启动totalProcess个进程
            toPro = totalProcess < maxParallelProcess ? totalProcess : maxParallelProcess;
            for (int i = 0; i < toPro; i++)
            {
                doneProcess++;
                DoEvents2();
            }
            //任务全部执行后再结束主进程
            while (doneProcess < totalProcess)
            {

            }
        }

        /// <summary>
        /// 执行进程
        /// </summary>
        private  void DoEvents2()
        {
            ProcessStartInfo processInfo = new ProcessStartInfo();
            processInfo.FileName = @"C:\进程.exe";
            processInfo.Arguments = (doneProcess).ToString();
            Process pro = new Process();
            pro.EnableRaisingEvents = true;
            pro.StartInfo = processInfo;
            pro.Exited += new EventHandler(process_Exited2);
            pro.Start();
            //pro.WaitForExit(18000)//等待最多18秒退出进程
        }

        /// <summary>
        /// 进程结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       private void process_Exited2(object sender, EventArgs e)
        {
            doneProcess++;
            toPro--;//第一次要启动的四个进程还没有完全启动
            if (doneProcess <= totalProcess)
            {
                DoEvents2();//结束一个进程,再启动一个进程
            }
        }
    }
}

三、进程

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

namespace 进程
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(string.Format("这是第{0}个进程", args));
            Thread.Sleep(3000);
        }
    }
}

四、用户调用

<Window x:Class="进程并行.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Width" Value="50"></Setter>
            <Setter Property="Height" Value="50"></Setter>
            <Setter Property="HorizontalAlignment" Value="Center"></Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="Background" Value="Blue"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Button Click="Button_Click_1">方法1</Button>
        <Button Grid.Row="1" Click="Button_Click_2">方法2</Button>
    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 进程并行
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 方法1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            StartProcess1 proStart1 = new StartProcess1();
            proStart1.Do();
        }

        /// <summary>
        /// 方法2
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            StartProcess2 proStart2 = new StartProcess2();
            proStart2.Do2();
        }
    }
}

时间: 2024-08-19 13:01:34

C#多进程并行的相关文章

[小知识]Shell控制多进程并行 @ Shell

Shell控制程序多进程并行执行需要使用for循环. #!/bin/bash for i in *.py do nohup python $i & done wait python b.py 比如以上这段代码,多进程并行执行当前目录的所有.py文件,wait关键字表示等待所有的python程序执行完成以后,再执行b.py文件.

python多进程并行代码

from multiprocessing import Process import sys, os import time def timetask(string): while True: print(string) def works(func, arg, worknum): proc_record = [] for i in range(worknum): p = Process(target = func, args = (i,)) p.start() proc_record.appe

python多进程并行执行和顺序执行的时间测试

#_*_coding:utf-8_*_ import time from  multiprocessing import Pool from threading import Thread def func1(fn):     time.sleep(1)     return fn * fn if __name__ == "__main__":     a = [1,2,3,4,5,6]     print "顺序执行的方式开始..."     s = time.t

1.1 什么是并行

在最简单最基础的层面上说,并行是指两个或更多的动作在同一时间发生,我们遇到的并行是生活中自然存在的,我们可以边说话边走或者每只手都进行不同的动作,当然我们每个人都是我们的生活中彼此独立的,你可以去看足球比赛当我游泳的时候,等等. 1.1.1 计算机中的并行 当我们讨论计算机的并行时,我们指一个系统执行多个独立的任务,而不是按顺序,或者一个接一个的,它不是一个新的现象:多任务操作系统允许一个计算机同时运行多个程序尽管任务切换已经初见很多年了.但是高端服务器的多进程的真实并行被使用更久.真实的运行多

Python多线程多进程那些事儿看这篇就够了~~

自己以前也写过多线程,发现都是零零碎碎,这篇写写详细点,填一下GIL和Python多线程多进程的坑~ 总结下GIL的坑和python多线程多进程分别应用场景(IO密集.计算密集)以及具体实现的代码模块. 目录   0x01 进程 and 线程 and “GIL” 0x02 python多线程&&线程锁&&threading类 0x03 python队列代码实现 0x04 python之线程池实现 0x05 python多进程并行实现 0x01 进程 and 线程 and “

(数据科学学习手札70)面向数据科学的Python多进程简介及应用

本文对应脚本已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 一.简介 进程是计算机系统中资源分配的最小单位,也是操作系统可以控制的最小单位,在数据科学中很多涉及大量计算.CPU密集型的任务都可以通过多进程并行运算的方式大幅度提升运算效率从而节省时间开销,而在Python中实现多进程有多种方式,本文就将针对其中较为易用的几种方式进行介绍. 二.利用multiprocessing实现多进程 multiprocessin

linux进程同步机制_转

转自:Linux进程同步机制 具体应用可参考:线程同步       IPC之信号量 为了能够有效的控制多个进程之间的沟通过程,保证沟通过程的有序和和谐,OS必须提供一 定的同步机制保证进程之间不会自说自话而是有效的协同工作.比如在共享内存的通信方式中,两个或者多个进程都要对共享的内存进行数据写入,那么怎么才能保证一个进程在写入的过程中不被其它的进程打断,保证数据的完整性呢?又怎么保证读取进程在读取数据的过程中数据不会变动,保证读取出的数据是完整有效的 呢?常用的同步方式有: 互斥锁.条件变量.读

[python] 线程简介

参考:http://www.cnblogs.com/aylin/p/5601969.html 我是搬运工,特别感谢张岩林老师! python 线程与进程简介 进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CPU是计算机的核心,它承担计算机的所有任务. 操作系统是运行在硬件之上的软件,是计算机的管理者,它负责资源的管理和分配.任务的调度. 程序是运行在系统上的具有某种功能的软件,比如说浏览器,音乐播放器等. 每次执行程序的时候,都会完成一定的功能,比如说浏览器帮我们打开网页,为了

python中的进程、线程(threading、multiprocessing、Queue、subprocess)

Python中的进程与线程 学习知识,我们不但要知其然,还是知其所以然.你做到了你就比别人NB. 我们先了解一下什么是进程和线程. 进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CPU是计算机的核心,它承担计算机的所有任务. 操作系统是运行在硬件之上的软件,是计算机的管理者,它负责资源的管理和分配.任务的调度. 程序是运行在系统上的具有某种功能的软件,比如说浏览器,音乐播放器等. 每次执行程序的时候,都会完成一定的功能,比如说浏览器帮我们打开网页,为了保证其独立性,就需要一个专