C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > c#并行编程

c#并行编程示例分享

作者:

这篇文章主要介绍了c#并行编程示例,大家直接看下面的代码吧

ParallelTest.cs

复制代码 代码如下:

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

namespace ParallelTest
{
    class ParallelTest
    {
        private static int Timed_Message(String arg_Message, int arg_Interval)
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Source {0} - Cycle {1} for Interval {2}", arg_Message, i, arg_Interval);
                Thread.Sleep(1000 * arg_Interval);
            }

            Console.WriteLine("{0} - Complete", arg_Message);
            return 0;
        }

        static void Main(string[] args)
        {
            int RetCode = 0;
            Task RedistributionTask = new Task(() => RetCode = Timed_Message("Five ", 4));
            RedistributionTask.Start();
            Task AltRedistributionTask = new Task(() => RetCode = Timed_Message("Three ", 2));
            AltRedistributionTask.Start();
            //Timed_Message("Main", 6);

            // wait for input before exiting
            Console.WriteLine("Press enter to finish after both [Complete] messages appear.");
            Console.ReadLine();
        }
    }
}

输出结果

复制代码 代码如下:

Press enter to finish after both [Complete] messages appear.
Source Five  - Cycle 0 for Interval 4
Source Three  - Cycle 0 for Interval 2
Source Three  - Cycle 1 for Interval 2
Source Five  - Cycle 1 for Interval 4
Source Three  - Cycle 2 for Interval 2
Source Three  - Cycle 3 for Interval 2
Source Five  - Cycle 2 for Interval 4
Source Three  - Cycle 4 for Interval 2
Source Three  - Cycle 5 for Interval 2
Source Five  - Cycle 3 for Interval 4
Source Three  - Cycle 6 for Interval 2
Source Three  - Cycle 7 for Interval 2
Source Five  - Cycle 4 for Interval 4
Source Three  - Cycle 8 for Interval 2
Source Three  - Cycle 9 for Interval 2
Source Five  - Cycle 5 for Interval 4
Three  - Complete
Source Five  - Cycle 6 for Interval 4
Source Five  - Cycle 7 for Interval 4
Source Five  - Cycle 8 for Interval 4
Source Five  - Cycle 9 for Interval 4
Five  - Complete

您可能感兴趣的文章:
阅读全文