• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Threading.EventWaitHandle类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Threading.EventWaitHandle的典型用法代码示例。如果您正苦于以下问题:C# EventWaitHandle类的具体用法?C# EventWaitHandle怎么用?C# EventWaitHandle使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



EventWaitHandle类属于System.Threading命名空间,在下文中一共展示了EventWaitHandle类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Main

        public static void Main(string[] args)
        {

            var done = new EventWaitHandle(false, EventResetMode.AutoReset);

            var yield = new Thread(
                new ParameterizedThreadStart(
                    data =>
                    {
                        Console.WriteLine(new { data });

                        done.Set();
                    }
                )
            );

            Console.WriteLine("before wait " + DateTime.Now);

            // Additional information: Thread has not been started.
            done.WaitOne(2100);

            Console.WriteLine("after wait " + DateTime.Now);

            yield.Start(new { foo = "bar" });

            done.WaitOne();

            Console.WriteLine("done");

            CLRProgram.CLRMain();
        }
开发者ID:exaphaser,项目名称:JSC-Cross-Compiler,代码行数:31,代码来源:Program.cs


示例2: DebuggerStart

    private void DebuggerStart(EventWaitHandle startWaitHandle, Func<ProcessInformation> processCreator, Action<ProcessInformation> callback, Action<Exception> errorCallback) {
      try {
        _debuggerThread = Thread.CurrentThread;
        // Note: processCreator is responsible for creating the process in DEBUG mode.
        // Note: If processCreator throws an exception after creating the
        // process, we may end up in a state where we received debugging events
        // without having "_processInformation" set. We need to be able to deal
        // with that.
        _processInformation = processCreator();
        callback(_processInformation);
      }
      catch (Exception e) {
        errorCallback(e);
        return;
      }
      finally {
        startWaitHandle.Set();
      }

      _running = true;
      try {
        DebuggerLoop();
      }
      finally {
        _running = false;
      }
    }
开发者ID:mbbill,项目名称:vs-chromium,代码行数:27,代码来源:DebuggerThread.cs


示例3: ActivateThreaded

		/// <summary>
		/// Turns this panel into multi-threaded mode.
		/// This will sort of glitch out other gdi things on the system, but at least its fast...
		/// </summary>
		public void ActivateThreaded()
		{
			ewh = new EventWaitHandle(false, EventResetMode.AutoReset);
			threadPaint = new Thread(PaintProc);
			threadPaint.IsBackground = true;
			threadPaint.Start();
		}
开发者ID:henke37,项目名称:BizHawk,代码行数:11,代码来源:ViewportPanel.cs


示例4: ResponseListener

 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="session"></param>
 public ResponseListener(O2GSession session)
 {
     mRequestID = string.Empty;
     mResponse = null;
     mSyncResponseEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
     mSession = session;
 }
开发者ID:fxcmapidavid,项目名称:Forex-Connect,代码行数:11,代码来源:ResponseListener.cs


示例5: Main

        public static void Main(string[] args)
        {
            var dir = @"c:\tmp";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

            for (int i = 0; i <= 10; i++)
            {
                var t = new Thread(ThreadProc);
                t.Start(i);
                Console.WriteLine("Tread {0} started", i);
            }

            watcher = new FileSystemWatcher()
            {
                Path = dir,
                IncludeSubdirectories = false,
                EnableRaisingEvents = true,
            };

            watcher.Created += (sender, eventArgs) =>
            {
                 ewh.Set();
            };

            Console.WriteLine("Press any key....");
            Console.ReadLine();
        }
开发者ID:microcourse,项目名称:comda,代码行数:32,代码来源:Program.cs


示例6: HttpChannelListenerEntry

		public HttpChannelListenerEntry (ChannelDispatcher channel, EventWaitHandle waitHandle)
		{
			ChannelDispatcher = channel;
			WaitHandle = waitHandle;
			ContextQueue = new Queue<HttpContextInfo> ();
			RetrieverLock = new object ();
		}
开发者ID:nickchal,项目名称:pash,代码行数:7,代码来源:HttpChannelListenerEntry.cs


示例7: EndProfile

 private void EndProfile(RequestItem pending, IRestResponse response, EventWaitHandle signal)
 {
     TimeSpan elapsed = pending.Elapsed;
     network.Profile(response, pending.Started, elapsed);
     network.ProfilePendingRemove(pending);
     signal.Set();
 }
开发者ID:bevacqua,项目名称:Swarm,代码行数:7,代码来源:VirtualUser.cs


示例8: FetchSchema

        /// <summary>
        /// Fetches the Tf2 Item schema.
        /// </summary>
        /// <param name="apiKey">The API key.</param>
        /// <returns>A  deserialized instance of the Item Schema.</returns>
        /// <remarks>
        /// The schema will be cached for future use if it is updated.
        /// </remarks>
        public static Schemazh FetchSchema()
        {
            var url = SchemaApiUrlBase;

            // just let one thread/proc do the initial check/possible update.
            bool wasCreated;
            var mre = new EventWaitHandle(false,
                EventResetMode.ManualReset, SchemaMutexName, out wasCreated);

            // the thread that create the wait handle will be the one to
            // write the cache file. The others will wait patiently.
            if (!wasCreated)
            {
                bool signaled = mre.WaitOne(10000);

                if (!signaled)
                {
                    return null;
                }
            }

            HttpWebResponse response = Drop.SteamWeb.Request(url, "GET");

            DateTime schemaLastModified = DateTime.Parse(response.Headers["Last-Modified"]);

            string result = GetSchemaString(response, schemaLastModified);

            response.Close();

            // were done here. let others read.
            mre.Set();

            SchemaResult schemaResult = JsonConvert.DeserializeObject<SchemaResult>(result);
            return schemaResult.result ?? null;
        }
开发者ID:sy1989,项目名称:Dota2DroplistJson,代码行数:43,代码来源:Schemazh.cs


示例9: IsFirstInstance

    /// <summary>
    /// Creates the single instance.
    /// </summary>
    /// <param name="name">The name.</param>
    /// <returns></returns>
    public static bool IsFirstInstance(string name)
    {
      EventWaitHandle eventWaitHandle = null;
      string eventName = string.Format("{0}-{1}", Environment.MachineName, name);

      var isFirstInstance = false;

      try
      {
        // try opening existing wait handle
        eventWaitHandle = EventWaitHandle.OpenExisting(eventName);
      }
      catch
      {
        // got exception = handle wasn't created yet
        isFirstInstance = true;
      }

      if (isFirstInstance)
      {
        // init handle
        eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName);

        // register wait handle for this instance (process)
        ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, null, Timeout.Infinite, false);
        eventWaitHandle.Close();
      }

      return isFirstInstance;
    }
开发者ID:cornelius90,项目名称:InnovatorAdmin,代码行数:35,代码来源:SingleInstance.cs


示例10: Start

        public void Start(EventWaitHandle startEventHandle)
        {
            Contract.Requires<ArgumentNullException>(startEventHandle != null, "startEventHandle");

            if (!Active)
            {
                var waitHandle = new ManualResetEventSlim(false);

                lock (_listener)
                {
                    _shuttingDown = false;

                    _listener.Start();

                    _acceptSocketThread = new Thread(AcceptSocketLoop);

                    _acceptSocketThread.Start(waitHandle);
                }

                waitHandle.Wait();

                _logger.DebugFormat("started on {0}", LocalEndPoint);
            }

            startEventHandle.Set();
        }
开发者ID:hanswolff,项目名称:FryProxy,代码行数:26,代码来源:HttpProxyWorker.cs


示例11: ResolveToString

        public override string ResolveToString()
        {
            if (!Parameters.Contains("url") || string.IsNullOrEmpty(Parameters["url"].ToString()))
                throw new InvalidOperationException();

            string url = Parameters["url"].ToString();

            string resultString = null;

            using (var wc = new WebClient())
            {
                var tlock = new EventWaitHandle(false, EventResetMode.ManualReset);
                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) =>
                {
                    // TODO: Add progress monitoring
                });
                wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler((sender, e) =>
                {
                    resultString = e.Result;
                    tlock.Set();
                });
                wc.DownloadStringAsync(new Uri(url));
                tlock.WaitOne();
                tlock.Dispose();
            }

            return resultString;
        }
开发者ID:Craftitude-Team,项目名称:Craftitude-ClientApi,代码行数:28,代码来源:DownloadResolver.cs


示例12: Message

        /// <summary>
        /// Constructor for a message with or without waiting mechanism
        /// </summary>
        /// <param name="action"></param>
        /// <param name="waitForInvocation">When true, the message creator requires a waiting mechanism</param>
        public Message(Action action, bool waitForInvocation)
        {
            this.m_action = action;

            if (waitForInvocation) this.m_waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
            else this.m_waitHandle = null;
        }
开发者ID:wow4all,项目名称:evemu_server,代码行数:12,代码来源:Message.cs


示例13: CreateSingleInstance

        public static bool CreateSingleInstance(string name, EventHandler<InstanceCallbackEventArgs> callback, string[] args)
        {
            string eventName = string.Format("{0}-{1}", Environment.MachineName, name);

            InstanceProxy.IsFirstInstance = false;
            InstanceProxy.CommandLineArgs = args;

            try
            {
                using (EventWaitHandle eventWaitHandle = EventWaitHandle.OpenExisting(eventName))
                {
                    UpdateRemoteObject(name);

                    if (eventWaitHandle != null) eventWaitHandle.Set();
                }

                Environment.Exit(0);
            }
            catch
            {
                InstanceProxy.IsFirstInstance = true;

                using (EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName))
                {
                    ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, callback, Timeout.Infinite, false);
                }

                RegisterRemoteType(name);
            }

            return InstanceProxy.IsFirstInstance;
        }
开发者ID:noscripter,项目名称:ShareX,代码行数:32,代码来源:ApplicationInstanceManager.cs


示例14: Installer

        public Installer(string filename)
        {
            try {
                MsiFilename = filename;
                Task.Factory.StartNew(() => {
                    // was coapp just installed by the bootstrapper?
                    if (((AppDomain.CurrentDomain.GetData("COAPP_INSTALLED") as string) ?? "false").IsTrue()) {
                        // we'd better make sure that the most recent version of the service is running.
                        EngineServiceManager.InstallAndStartService();
                    }
                    InstallTask = LoadPackageDetails();
                });

                bool wasCreated;
                var ewhSec = new EventWaitHandleSecurity();
                ewhSec.AddAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow));
                _ping = new EventWaitHandle(false, EventResetMode.ManualReset, "BootstrapperPing", out wasCreated, ewhSec);

                // if we got this far, CoApp must be running.
                try {
                    Application.ResourceAssembly = Assembly.GetExecutingAssembly();
                } catch {
                }

                _window = new InstallerMainWindow(this);
                _window.ShowDialog();

                if (Application.Current != null) {
                    Application.Current.Shutdown(0);
                }
                ExitQuick();
            } catch (Exception e) {
                DoError(InstallerFailureState.FailedToGetPackageDetails, e);
            }
        }
开发者ID:ericschultz,项目名称:coapp,代码行数:35,代码来源:Installer.cs


示例15: SharedMemoryListener

 public SharedMemoryListener(IPCPeer peer)
 {
     _waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, EventName);
     _exit = false;
     _peer = peer;
     _lastSyncedVersion = null;
 }
开发者ID:alongubkin,项目名称:watchog,代码行数:7,代码来源:SharedMemoryListener.cs


示例16: Execute

        public override bool Execute()
        {
            try
            {
                syncEventName = new TaskItem(Guid.NewGuid().ToString());
                
                handle = new EventWaitHandle(false, EventResetMode.ManualReset, syncEventName.ItemSpec);
                handle.Reset();

                threadLock = GetLock(lockName);

                new Thread(new ThreadStart(AsyncExecute)).Start();

                while (m_AsyncThreadState == ThreadState.NOT_STARTED)
                {
                    Thread.Sleep(500);
                }
                
                return true;
            }
            catch (Exception e)
            {
                try
                {
                    Log.LogErrorFromException(e);
                }
                catch { }
                return false;
            }
        }
开发者ID:aura1213,项目名称:netmf-interpreter,代码行数:30,代码来源:AsyncExecBuildTask.cs


示例17: SetUp

 public void SetUp()
 {
     server = new WebSocketServer(URI.Port);
     server.AddService<Echo>(URI.AbsolutePath);
     server.Start();
     handle = new EventWaitHandle(false, EventResetMode.AutoReset);
 }
开发者ID:wsky,项目名称:top-link,代码行数:7,代码来源:WebSocketChannelTest.cs


示例18: ThreadWorker

		public ThreadWorker (IScheduler sched, ThreadWorker[] others, IProducerConsumerCollection<Task> sharedWorkQueue,
		                     bool createThread, int maxStackSize, ThreadPriority priority, EventWaitHandle handle)
		{
			this.others          = others;

			this.dDeque = new CyclicDeque<Task> ();
			
			this.sharedWorkQueue = sharedWorkQueue;
			this.workerLength    = others.Length;
			this.isLocal         = !createThread;
			this.waitHandle      = handle;
			
			this.childWorkAdder = delegate (Task t) { 
				dDeque.PushBottom (t);
				sched.PulseAll ();
			};
			
			// Find the stealing start index randomly (then the traversal
			// will be done in Round-Robin fashion)
			do {
				this.stealingStart = r.Next(0, workerLength);
			} while (others[stealingStart] == this);
			
			InitializeUnderlyingThread (maxStackSize, priority);
		}
开发者ID:stabbylambda,项目名称:mono,代码行数:25,代码来源:ThreadWorker.cs


示例19: BK8500

        public BK8500(string comPortname, byte address)
        {
            instrumentError = false;

            //Setup serial port
            P = new SerialPort(comPortname, 38400);
            P.DataBits = 8;
            P.StopBits = StopBits.One;
            P.Parity = Parity.None;
            P.RtsEnable = true;
            P.ReadTimeout = 200;

            //Setup event for received data
            P.ReceivedBytesThreshold = packetLength;  //all packets for this device are 26 bytes in length
            P.DataReceived += new SerialDataReceivedEventHandler(P_DataReceived);
            dataWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);  //this syncs the received data event handler to the main thread

            P.Open();
            P.DiscardInBuffer();
            this.address = address;

            //enter local mode
            this.remoteOperation = true;
            this.loadON = false;
            this.deviceConnected = true;
        }
开发者ID:jcoenraadts,项目名称:instruments,代码行数:26,代码来源:BK8500.cs


示例20: AbsoluteTimerWaitHandle

        public AbsoluteTimerWaitHandle(DateTimeOffset dueTime)
        {
            _dueTime = dueTime;
            _eventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

            SafeWaitHandle = _eventWaitHandle.SafeWaitHandle;

            var dueSpan = (_dueTime - DateTimeOffset.Now);
            var period = new TimeSpan(dueSpan.Ticks / 10);

            if (dueSpan < TimeSpan.Zero)
            {
                _eventWaitHandle.Set();
            }
            else
            {
                _timer = new Timer(period.TotalMilliseconds)
                {
                    AutoReset = false,
                };

                _timer.Elapsed += TimerOnElapsed;

                _timer.Start();
            }
        }
开发者ID:hash,项目名称:trigger.net,代码行数:26,代码来源:PlatformIndependentNative.cs



注:本文中的System.Threading.EventWaitHandle类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Threading.ExecutionContext类代码示例发布时间:2022-05-26
下一篇:
C# Threading.CountdownEvent类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap