-
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