欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#并行编程示例分享

程序员文章站 2023-12-21 12:02:40
paralleltest.cs 复制代码 代码如下:using system;using system.collections.generic;using system.l...

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

上一篇:

下一篇: