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