zoukankan      html  css  js  c++  java
  • c# AutoResetEvent

    前言

    在异步中如何控制两个线程这样运动呢,在A线程执行到某个位置的时候等待B线程执行,然后B运行到某个位置有又开始运行A,这时候可以用AutoResetEvent。

    正文

    代码:

    private static AutoResetEvent _workerEvent = new AutoResetEvent(false);
    private static AutoResetEvent _mainEvent = new AutoResetEvent(false);
    static void Main(string[] args)
    {
    	var t = new Thread(() => Process(10));
    	t.Start();
    	Console.WriteLine("start process sign!");
    	_workerEvent.WaitOne();
    	Thread.Sleep(TimeSpan.FromSeconds(5));
    	_mainEvent.Set();
    	Console.WriteLine("_workerEvent ");
    	_workerEvent.WaitOne();
    }
    
    static void Process(int seconds)
    {
    	Console.WriteLine("Starting a long running work....");
    	Thread.Sleep(TimeSpan.FromSeconds(2));
    	Console.WriteLine("Work is done");
    	_workerEvent.Set();
    	Console.WriteLine("Waiting for a main thread to complete its work");
    	_mainEvent.WaitOne();
    	Console.WriteLine("Starting second operation....");
    	Console.WriteLine("Work is done!");
    	Console.WriteLine("_workerEvent release ");
    	_workerEvent.Set();
    }
    

    这个可以自己跑一遍。

    后续

    原理后续补齐。

  • 相关阅读:
    SVN导入maven项目
    jQuery (二)DOM 操作
    jQuery (一)选择器
    jQuery 初识
    mysql的OFFSET实现分页
    MongoDB学习之(三)增删查改
    java安全性的一种简单思路
    java Spring 事务的初次使用与验证
    C#语法之匿名函数和Lambda表达式
    C#语法之委托和事件
  • 原文地址:https://www.cnblogs.com/aoximin/p/13220093.html
Copyright © 2011-2022 走看看