zoukankan      html  css  js  c++  java
  • From MSDN:WaitHandle

    The following code example shows how two threads can do background tasks while the Main thread waits for the tasks to complete using the static WaitAny and WaitAll methods of the WaitHandle class.

    using System;
    using System.Threading;

    public sealed class App
    {
    // Define an array with two AutoResetEvent WaitHandles.
    static WaitHandle[] waitHandles = new WaitHandle[]
    {
    new AutoResetEvent(false),
    new AutoResetEvent(false)
    };

    // Define a random number generator for testing.
    static Random r = new Random();

    static void Main()
    {
    // Queue up two tasks on two different threads;
    // wait until all tasks are completed.
    DateTime dt = DateTime.Now;
    Console.WriteLine("Main thread is waiting for BOTH tasks to complete.");
    ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[0]);
    ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[1]);
    WaitHandle.WaitAll(waitHandles);
    // The time shown below should match the longest task.
    Console.WriteLine("Both tasks are completed (time waited={0})",
    (DateTime.Now - dt).TotalMilliseconds);

    // Queue up two tasks on two different threads;
    // wait until any tasks are completed.
    dt = DateTime.Now;
    Console.WriteLine();
    Console.WriteLine("The main thread is waiting for either task to complete.");
    ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[0]);
    ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[1]);
    int index = WaitHandle.WaitAny(waitHandles);
    // The time shown below should match the shortest task.
    Console.WriteLine("Task {0} finished first (time waited={1}).",
    index + 1, (DateTime.Now - dt).TotalMilliseconds);
    }

    static void DoTask(Object state)
    {
    AutoResetEvent are = (AutoResetEvent) state;
    int time = 1000 * r.Next(2, 10);
    Console.WriteLine("Performing a task for {0} milliseconds.", time);
    Thread.Sleep(time);
    are.Set();
    }
    }

    // This code produces output similar to the following:
    //
    // Main thread is waiting for BOTH tasks to complete.
    // Performing a task for 7000 milliseconds.
    // Performing a task for 4000 milliseconds.
    // Both tasks are completed (time waited=7064.8052)
    //
    // The main thread is waiting for either task to complete.
    // Performing a task for 2000 milliseconds.
    // Performing a task for 2000 milliseconds.
    // Task 1 finished first (time waited=2000.6528).

    魔兽就是毒瘤,大家千万不要玩。
  • 相关阅读:
    过滤器
    自定义指令
    Window setTimeout() 方法
    Window setInterval()方法
    ThingJS官方案例(五):物联网室内3D定位导航,上下楼怎么办?
    基于WebGL的虚拟太阳系漫游技术实现 ThingJS 科幻片
    ThingJS官方案例(四):快速应用3D场景下的模拟导航能力
    ThingJS官方示例(三):3D标记“Marker”跳跃、闪烁和发光动画效果
    ThingJS官方示例(二):利用电子标注判断物联网设备的位置
    ThingJS 官方示例(一):禁区告警的3D电子围栏可视化
  • 原文地址:https://www.cnblogs.com/tracy/p/1763421.html
Copyright © 2011-2022 走看看