当前位置: 首页>>代码示例>>C#>>正文


C# AutoResetEvent.Dispose方法代码示例

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


在下文中一共展示了AutoResetEvent.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CanCaptureAudio

        public void CanCaptureAudio()
        {
            int n = 0;
            SoundInTests((c) =>
            {
                for (int i = 0; i < 500; i++)
                {
                    var waitHandle = new AutoResetEvent(true);

                    c.DataAvailable += (s, e) =>
                    {
                        waitHandle.Reset();
                    };

                    c.Initialize();
                    c.Start();

                    if (!waitHandle.WaitOne(2000))
                        Assert.Fail("Timeout");
                    else
                    {
                        Debug.WriteLine(n.ToString());
                        n++;
                    }

                    c.Stop();

                    waitHandle.Dispose();
                }
            });
        }
开发者ID:CheViana,项目名称:AudioLab,代码行数:31,代码来源:SoundInBehaviourTests.cs

示例2: Should_release_the_pool

        public void Should_release_the_pool()
        {
            // Arrange
            var blockTheThread = new AutoResetEvent(false);
            var countdownEvent = new CountdownEvent(1);

            var queue = Substitute.For<IInMemoryPriorityQueue<GenericPriorityMessage<BasicDeliverEventArgs>>>();
            queue.When(x => x.Dequeue()).Do(callInfo => { countdownEvent.Signal(); blockTheThread.WaitOne(); });
            
            var consumer = new PriorityBurrowConsumer(Substitute.For<IModel>(), Substitute.For<IMessageHandler>(), Substitute.For<IRabbitWatcher>(), false, 1);
            consumer.Init(queue, Substitute.For<CompositeSubscription>(), 1, Guid.NewGuid().ToString());
            consumer.Ready();
            

            // Action
            countdownEvent.Wait();
            countdownEvent.Reset();
            blockTheThread.Set();
            consumer.MessageHandlerHandlingComplete(null);
            countdownEvent.Wait();
            // Assert
            
            queue.Received(2).Dequeue();
            consumer.Dispose();
            blockTheThread.Dispose();
        }
开发者ID:sovanesyan,项目名称:Burrow.NET,代码行数:26,代码来源:MethodMessageHandlerHandlingComplete.cs

示例3: BackgroundDispatcher

        public BackgroundDispatcher(string name)
        {
            AutoResetEvent are = new AutoResetEvent(false);

            Thread thread = new Thread((ThreadStart)delegate
            {
                _dispatcher = Dispatcher.CurrentDispatcher;
                _dispatcher.UnhandledException +=
                delegate(
                     object sender,
                     DispatcherUnhandledExceptionEventArgs e)
                {
                    e.Handled = true;
                };
                are.Set();
                Dispatcher.Run();
            });

            thread.Name = string.Format("BackgroundStaDispatcher({0})", name);
            thread.SetApartmentState(ApartmentState.MTA);
            thread.IsBackground = true;
            thread.Start();

            are.WaitOne();
            are.Close();
            are.Dispose();
        }
开发者ID:karthik20522,项目名称:SimpleDotImage,代码行数:27,代码来源:BackgroundDispatcher.cs

示例4: StartAsync

        public Task StartAsync()
        {
            System.Windows.Threading.Dispatcher.CurrentDispatcher.VerifyAccess();

            if (ClientConfig.EmbeddedServer == EmbeddedServerMode.None)
                throw new Exception();

            var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
            path = System.IO.Path.Combine(path, "Dwarrowdelf", "save");
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            var gameDir = path;

            bool cleanSaves = ClientConfig.CleanSaveDir;
            Guid save = Guid.Empty;

            m_saveManager = new SaveManager(gameDir);

            if (cleanSaves)
                m_saveManager.DeleteAll();
            else
                save = m_saveManager.GetLatestSaveFile();

            CreateEmbeddedServer(gameDir, save);

            var tcs = new TaskCompletionSource<object>();

            var serverStartWaitHandle = new AutoResetEvent(false);

            ThreadPool.RegisterWaitForSingleObject(serverStartWaitHandle,
                (o, timeout) =>
                {
                    serverStartWaitHandle.Dispose();

                    if (timeout)
                    {
                        m_serverThread.Abort();
                        tcs.SetException(new Exception("Timeout waiting for server"));
                    }
                    else
                    {
                        tcs.SetResult(null);
                    }
                },
                null, TimeSpan.FromSeconds(60), true);

            m_serverThread = new Thread(ServerMain);
            m_serverThread.Start(serverStartWaitHandle);

            return tcs.Task;
        }
开发者ID:Fulborg,项目名称:dwarrowdelf,代码行数:52,代码来源:EmbeddedServer.cs

示例5: StartAsync

        public Task StartAsync(EmbeddedServerOptions options)
        {
            if (options.ServerMode == EmbeddedServerMode.None)
                throw new Exception();

            m_serverMode = options.ServerMode;
            m_gameOptions = options.NewGameOptions;

            if (!System.IO.Directory.Exists(options.SaveGamePath))
                System.IO.Directory.CreateDirectory(options.SaveGamePath);

            Guid save = Guid.Empty;

            m_saveManager = new SaveManager(options.SaveGamePath);

            if (options.CleanSaveDir)
                m_saveManager.DeleteAll();
            else
                save = m_saveManager.GetLatestSaveFile();

            CreateEmbeddedServer(options.SaveGamePath, save);

            var tcs = new TaskCompletionSource<object>();

            var serverStartWaitHandle = new AutoResetEvent(false);

            ThreadPool.RegisterWaitForSingleObject(serverStartWaitHandle,
                (o, timeout) =>
                {
                    serverStartWaitHandle.Dispose();

                    if (timeout)
                    {
                        m_serverThread.Abort();
                        tcs.SetException(new Exception("Timeout waiting for server"));
                    }
                    else
                    {
                        tcs.SetResult(null);
                    }
                },
                null, TimeSpan.FromSeconds(60), true);

            m_serverThread = new Thread(ServerMain);
            m_serverThread.Start(serverStartWaitHandle);

            return tcs.Task;
        }
开发者ID:tomba,项目名称:dwarrowdelf,代码行数:48,代码来源:EmbeddedServer.cs

示例6: StartWithCallback

        public void StartWithCallback()
        {
            // arrange
            var loop = new EventLoop();
            var wait = new AutoResetEvent(false);

            // act
            loop.Start(() => wait.Set());

            // assert
            Assert.That(() => wait.WaitOne(100), Is.True);

            // cleanup
            loop.Dispose();
            wait.Dispose();
        }
开发者ID:oldslowfatstu,项目名称:NLoop,代码行数:16,代码来源:EventLoopTests.cs

示例7: Stop

        public void Stop()
        {
            // stops the timer and wait for the current operation to complete
            _logger.Info("Stopping Readers, waiting for remaining operations to complete...");
            processQueue.CompleteAdding();

            WaitHandle waitHandle = new AutoResetEvent(false);
            _readTimer.Dispose(waitHandle);
            waitHandle.WaitOne();
            waitHandle.Dispose();

            var tasks=new List<Task>();
            tasks.Add(_readTask);
            Task.WaitAll(tasks.ToArray());

            _logger.Info("Readers stopped");
        }
开发者ID:stanler,项目名称:web-service-reader-for-pi-system,代码行数:17,代码来源:DataReadersManager.cs

示例8: Schedule

        public void Schedule()
        {
            // arrange
            var loop = new EventLoop();
            var wait = new AutoResetEvent(false);
            var counter = 0;

            // act
            loop.Schedule(() => counter++);
            loop.Schedule(() => counter++);
            loop.Start(() => wait.Set());
            loop.Schedule(() => counter++);

            // assert
            Assert.That(() => wait.WaitOne(100), Is.True);
            Assert.That(counter, Is.EqualTo(3));

            // cleanup
            loop.Dispose();
            wait.Dispose();
        }
开发者ID:oldslowfatstu,项目名称:NLoop,代码行数:21,代码来源:EventLoopTests.cs

示例9: OnSettings

		void OnSettings()
		{
			StartupSettingsWaitHandler = new AutoResetEvent(false);
			ApplicationService.BeginInvoke(() =>
			{
				if (StartupSettingsWaitHandler != null)
				{
					StartupSettingsWaitHandler.WaitOne();
					StartupSettingsWaitHandler.Dispose();
				}
				StartupSettingsWaitHandler = null;
			});
			DialogService.ShowModalWindow(new StartupSettingsViewModel(_clientType));
			StartupSettingsWaitHandler.Set();
		}
开发者ID:xbadcode,项目名称:Rubezh,代码行数:15,代码来源:StartupViewModel.cs

示例10: ResetAndMoveIn

        public async Task ResetAndMoveIn()
        {
            _smartWindowSkin.DisableWindow();
            _advancedWindowSkin.DisableWindow();
            bool isadvancedwindow = HostedWindow != _smartWindowSkin;
            _smartWindowSkin = new WindowSmartView();
            _advancedWindowSkin = new WindowAdvancedView();
            ApplyHostWindow(isadvancedwindow ? _advancedWindowSkin : _smartWindowSkin, false);

            var outanimation = new ThicknessAnimation(new Thickness(-100, 0, 100, 0), new Thickness(0), TimeSpan.FromMilliseconds(350));
            var fadeanimation = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(400));
            var control = (DependencyObject)HostedWindow;

            Storyboard.SetTarget(outanimation, control);
            Storyboard.SetTarget(fadeanimation, control);

            Storyboard.SetTargetProperty(outanimation, new PropertyPath(MarginProperty));
            Storyboard.SetTargetProperty(fadeanimation, new PropertyPath(OpacityProperty));
            
            var story = new Storyboard();
            story.Children.Add(outanimation);
            story.Children.Add(fadeanimation);
            var handler = new AutoResetEvent(false);
            story.Completed += (s, e) => handler.Set();
            story.Begin(this);
            await Task.Run(() => handler.WaitOne());
            handler.Dispose();
            ResetFlyout();
        }
开发者ID:WELL-E,项目名称:Hurricane,代码行数:29,代码来源:MainWindow.xaml.cs

示例11: MoveOut

        public async Task MoveOut()
        {
            var fadeanimation = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(200));
            var control = (DependencyObject)HostedWindow;

            Storyboard.SetTarget(fadeanimation, control);

            Storyboard.SetTargetProperty(fadeanimation, new PropertyPath(OpacityProperty));

            var story = new Storyboard();
            story.Children.Add(fadeanimation);
            var handler = new AutoResetEvent(false);
            story.Completed += (s, e) => handler.Set();
            story.Begin(this);
            await Task.Run(() => handler.WaitOne());
            handler.Dispose();
        }
开发者ID:WELL-E,项目名称:Hurricane,代码行数:17,代码来源:MainWindow.xaml.cs

示例12: AddNewThreadToPool

        /// <summary>
        ///     Creates a new worker thread and adds it to the pool.
        /// </summary>
        /// <remarks>
        ///     The new thread has a ref count of 0.
        /// </remarks>
        /// <returns>
        ///     The dispatcher associated with the new worker thread.
        /// </returns>
        private static Dispatcher AddNewThreadToPool()
        {
            Debug.Assert(_numThreads < _maxThreads, "Creating a thread would exceed the maximum allowed!");

            AutoResetEvent isRunning = new AutoResetEvent(false);
            int threadId = _threadIdCounter++;

            // Spin up our worker thread.  The important aspects of this
            // thread are:
            // 1) It runs a WPF Dispatcher loop, which is a message pump.
            // 2) It is marked as STA.
            // 3) It is marked as a background thread, which will allow the
            //    app to exit even with active UIThreadPool threads.
            Thread thread = new Thread(new ParameterizedThreadStart(WorkerThreadMain));

            thread.Name = "UIThreadPoolThread #" + threadId;
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start(isRunning);

            // Wait for the worker thread to get started.
            isRunning.WaitOne();
            isRunning.Dispose();

            // Add the dispatcher to the list of free worker threads,
            Dispatcher dispatcher = Dispatcher.FromThread(thread);
            _poolThreads.Add(dispatcher, new Tuple<bool, int>(true, 0));
            _numThreads++;

            return dispatcher;
        }
开发者ID:JazzFisch,项目名称:AnotherCombatManager,代码行数:40,代码来源:UIThreadPool.cs

示例13: EndInvoke

        /// <summary>
        /// Wait for the operation to complete and throw the exception if any.
        /// </summary>
        internal void EndInvoke()
        {
            _invokeOnThreadEvent = new AutoResetEvent(false);

            // Start the thread wait loop.
            WaitHandle[] waitHandles = new WaitHandle[2] { AsyncWaitHandle, _invokeOnThreadEvent };
            bool waiting = true;
            while (waiting)
            {
                int waitIndex = WaitHandle.WaitAny(waitHandles);

                if (waitIndex == 0)
                {
                    waiting = false;
                }
                else
                {
                    // Invoke callback on thread.
                    try
                    {
                        _invokeCallback(_invokeCallbackState);
                    }
                    catch (Exception e)
                    {
                        CommandProcessorBase.CheckForSevereException(e);
                    }
                }
            }

            AsyncWaitHandle.Dispose();
            _completedWaitHandle = null;  // Allow early GC

            _invokeOnThreadEvent.Dispose();
            _invokeOnThreadEvent = null;  // Allow early GC

            // Operation is done: if an exception occured, throw it
            if (null != Exception)
            {
                throw Exception;
            }
        }
开发者ID:40a,项目名称:PowerShell,代码行数:44,代码来源:AsyncResult.cs

示例14: WaitForDeploymentComplete

        private void WaitForDeploymentComplete(string requestToken)
        {
            AutoResetEvent threadBlocker = null;
            try
            {
                threadBlocker = new AutoResetEvent(false);

                deployAppWaitTimer = new System.Timers.Timer(5000);
                deployAppWaitTimer.Elapsed += new ElapsedEventHandler(
                    delegate(object sender, ElapsedEventArgs e)
                    {
                        string requestUri;
                        string responseXml;
                        bool isError;

                        HttpWebRequest webRequest;
                        HttpWebResponse webResponse = null;
                        X509Certificate2 authCert;

                        try
                        {
                            Console.WriteLine("Getting deployment request status.");
                            deployAppWaitTimer.Stop();
                            authCert = GetAuthCertificate(certThumbprint);
                            requestUri = string.Format("https://management.core.windows.net/{0}/operations/{1}", subscriptionId, requestToken);

                            webRequest = (HttpWebRequest)WebRequest.Create(requestUri);
                            webRequest.Method = "GET";
                            webRequest.ClientCertificates.Add(authCert);
                            webRequest.Headers.Add("x-ms-version", "2009-10-01");

                            webResponse = (HttpWebResponse)webRequest.GetResponse();
                            if (webResponse.StatusCode != HttpStatusCode.OK)
                            {
                                throw new Exception(@"Error fetching status code for creating deployment. Error code - " +
                                                    webResponse.StatusCode.ToString() +
                                                    " Description - " + webResponse.StatusDescription);
                            }

                            using (Stream responseStream = webResponse.GetResponseStream())
                            using (StreamReader responseStreamReader = new StreamReader(responseStream))
                            {
                                responseXml = responseStreamReader.ReadToEnd();
                                if (IsDeploymentComplete(responseXml, out isError) == true)
                                {
                                    Console.WriteLine("Deployment successfull.");
                                    deployAppWaitTimer.Dispose();
                                    threadBlocker.Set();
                                }
                                else if (isError == true) //Give up.
                                {
                                    deployAppWaitTimer.Dispose();
                                    threadBlocker.Set();
                                }
                                else
                                {
                                    Console.WriteLine("Deployment not complete yet. System shall retry after 5 seconds.");
                                    deployAppWaitTimer.Start();
                                }
                            }
                        }
                        finally
                        {
                            if (webResponse != null) webResponse.Close();
                        }
                    });

                deployAppWaitTimer.Start();
                threadBlocker.WaitOne();
            }
            finally
            {
                if (threadBlocker != null) threadBlocker.Dispose();
            }
        }
开发者ID:enekazo,项目名称:Windows-Azure-Solr,代码行数:75,代码来源:DeployReplSolzr.cs

示例15: Stop

        public void Stop()
        {
            // If we're not running, then this is moot. Bail.
            if (m_refreshtimer == null)
            {
                return;
            }

            // Setup an event to handle waiting for our cleanup.
            AutoResetEvent cleanup = new AutoResetEvent(false);
            // Ask the timer to clean up.
            m_refreshtimer.Dispose(cleanup);
            // If the timer goes the larger of two extra cycles or 100ms and still hasn't stopped
            if (!cleanup.WaitOne(Math.Min(2 * m_period,100)))
            {
                // Die.
                throw new TimeoutException("Timer failed to stop.");
            }
            // cleanup our timer handle
            m_refreshtimer = null;

            // dispose our wait handle
            cleanup.Dispose();

            // Lastly, if the serial port is open (it should be.)
            if (m_targetport.IsOpen) {
                // Close it.
                m_targetport.Close();
            }
        }
开发者ID:JimTheCactus,项目名称:ScrollingMatrix,代码行数:30,代码来源:MatrixDisplayEngine.cs


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