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


C# System.Threading.ManualResetEvent.Reset方法代码示例

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


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

示例1: ConnectionManagerAddsNewServicesFromServiceDiscovery

        public void ConnectionManagerAddsNewServicesFromServiceDiscovery()
        {
            var manualResetEvent = new System.Threading.ManualResetEvent(false);
            var serviceUri1 = new ServiceUri() { Address = "1" };
            var serviceUri2 = new ServiceUri() { Address = "2" };
            Dictionary<ServiceUri, PerformanceStatistics> services
                = new Dictionary<ServiceUri, PerformanceStatistics>()
                {
                    {serviceUri1, new PerformanceStatistics()},
                    {serviceUri2, new PerformanceStatistics()}
                };
            var serviceDiscoveryMock = new Mock<IServiceDiscovery>(MockBehavior.Strict);
            serviceDiscoveryMock.Setup(sd => sd.GetPerformanceStatistics()).Returns(() => services).Callback(() => manualResetEvent.Set());

            var manager = new ConnectionManager(remoteService: null, listener: null,
                serviceDiscovery: serviceDiscoveryMock.Object,
                serviceDiscoveryPeriod: new TimeSpan(days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds: 10));

            manualResetEvent.WaitOne();
            manager.RemoteServices.Count().ShouldBe(2);
            services.Add(new ServiceUri(), new PerformanceStatistics());
            manualResetEvent.Reset();
            manualResetEvent.WaitOne();

            manager.RemoteServices.Count().ShouldBe(3);
        }
开发者ID:pbazydlo,项目名称:bluepath,代码行数:26,代码来源:ConnectionManagerTests.cs

示例2: Connection

 public Connection(ref System.Net.Sockets.TcpClient TCPClient, System.Threading.ManualResetEvent eventChannelConnectionComplete, ref CarverLab.Utility.Logger logger)
 {
     log = logger;
     log.Context = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
     m_TCPClient = TCPClient;
     m_bConnected = false;
     m_iBufferMaxLength = 2048;
     m_iBufferLength = 0;
     m_bytesIncomingBuffer = new byte[m_iBufferMaxLength];
     m_bDone = false;
     m_ThreadReceiveDataAndEnqueue = new System.Threading.Thread(new System.Threading.ThreadStart(this.ReceiveDataAndEnqueue));
     m_ThreadAutomaticDequeue = new System.Threading.Thread(new System.Threading.ThreadStart(this.DequeCommands));
     m_ThreadIsConnectionAlive = new System.Threading.Thread(new System.Threading.ThreadStart(this.IsConnectionAlive));
     m_qCommands = System.Collections.Queue.Synchronized(new System.Collections.Queue());
     m_EventChannelConnectionComplete = eventChannelConnectionComplete;
     m_EventChannelConnectionComplete.Reset();
     m_EventMessageAvailable = new System.Threading.AutoResetEvent(false);
     m_EventThreadComplete = new System.Threading.ManualResetEvent(false);
     m_bIsRunning = false;
     m_bAutomaticDequeueingSuspended = false;
     m_EventAutomaticQueueing = new System.Threading.ManualResetEvent(true);
 }
开发者ID:CarverLab,项目名称:Oyster,代码行数:22,代码来源:Connection.cs

示例3: ConvertTrack2

        /// <summary>
        /// Start converting the specified track. For a track in an audio CD playlist, this
        /// is equivalent to importing the song.  Use CurrentEncoder to set the current
        /// encoder before converting
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public Track ConvertTrack2(Track convertible)
        {
            return Invoke((Func<Track>)delegate
            {
                System.Threading.ManualResetEvent reset =
                    new System.Threading.ManualResetEvent(false);

                object refTrack = convertible.AsInternal;
                iTunesConvertOperationStatus status = itunes.ConvertTrack2(ref refTrack);

                status.OnConvertOperationCompleteEvent +=
                    delegate
                    {
                        // this anonymous callback delegate signals the scanner
                        // thread to continue...
                        reset.Set();
                    };

                // wait for the current conversion to complete, otherwise iTunes
                // raises an exception when concurrent conversions are requested
                reset.WaitOne();
                reset.Reset();
                reset = null;

                Track track = null;

                try
                {
                    if (status.Tracks.Count > 0)
                    {
                        track = new Track(status.Tracks[1]);
                    }
                }
                catch (NullReferenceException exc)
                {
                    // NullRefException can occur when iTunes displays the "protected" dialog.
                    // We cannot test if status.Tracks is even null because that alone will
                    // throw a COMException

                    throw new ProtectedException(
                        "Possible protection fault in Controller.ConvertTrack2", exc);
                }
                finally
                {
                    Release(status);
                }

                return track;
            });
        }
开发者ID:pengyancai,项目名称:cs-util,代码行数:57,代码来源:Controller.cs

示例4: ConvertFile2

        /// <summary>
        /// Start converting the specified file or folder.  The file or files will added to the
        /// main library after conversion. For a file on an audio CD, this is equivalent to
        /// importing the song.  Use CurrentEncoder to set the current encoder before converting.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public Track ConvertFile2(string path)
        {
            return Invoke((Func<Track>)delegate
            {
                System.Threading.ManualResetEvent reset =
                    new System.Threading.ManualResetEvent(false);

                iTunesConvertOperationStatus status = itunes.ConvertFile2(path);

                status.OnConvertOperationCompleteEvent +=
                    delegate
                    {
                        // this anonymous callback delegate signals the scanner
                        // thread to continue...
                        reset.Set();
                    };

                // wait for the current conversion to complete, otherwise iTunes
                // raises an exception when concurrent conversions are requested
                reset.WaitOne();
                reset.Reset();
                reset = null;

                Track track = null;

                if (status.Tracks.Count > 0)
                {
                    track = new Track(status.Tracks[1]);
                }

                Release(status);

                return track;
            });
        }
开发者ID:pengyancai,项目名称:cs-util,代码行数:42,代码来源:Controller.cs

示例5: Run

        public void Run(
            EasyHook.RemoteHooking.IContext context,
            String channelName,
            CaptureConfig config)
        {
            // When not using GAC there can be issues with remoting assemblies resolving correctly
            // this is a workaround that ensures that the current assembly is correctly associated
            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.AssemblyResolve += (sender, args) =>
            {
                return this.GetType().Assembly.FullName == args.Name ? this.GetType().Assembly : null;
            };

            // NOTE: This is running in the target process
            _interface.Message(MessageType.Information, "Injected into process Id:{0}.", EasyHook.RemoteHooking.GetCurrentProcessId());

            _runWait = new System.Threading.ManualResetEvent(false);
            _runWait.Reset();
            try
            {
                // Initialise the Hook
                if (!InitialiseDirectXHook(config))
                {
                    return;
                }
                _interface.Disconnected += _clientEventProxy.DisconnectedProxyHandler;

                // Important Note:
                // accessing the _interface from within a _clientEventProxy event handler must always 
                // be done on a different thread otherwise it will cause a deadlock

                _clientEventProxy.Disconnected += () =>
                {
                    // We can now signal the exit of the Run method
                    _runWait.Set();
                };

                // We start a thread here to periodically check if the host is still running
                // If the host process stops then we will automatically uninstall the hooks
                StartCheckHostIsAliveThread();

                // Wait until signaled for exit either when a Disconnect message from the host 
                // or if the the check is alive has failed to Ping the host.
                _runWait.WaitOne();

                // we need to tell the check host thread to exit (if it hasn't already)
                StopCheckHostIsAliveThread();

                // Dispose of the DXHook so any installed hooks are removed correctly
                DisposeDirectXHook();
            }
            catch (Exception e)
            {
                _interface.Message(MessageType.Error, "An unexpected error occured: {0}", e.ToString());
            }
            finally
            {
                try
                {
                    _interface.Message(MessageType.Information, "Disconnecting from process {0}", EasyHook.RemoteHooking.GetCurrentProcessId());
                }
                catch
                {
                }

                // Remove the client server channel (that allows client event handlers)
                System.Runtime.Remoting.Channels.ChannelServices.UnregisterChannel(_clientServerChannel);

                // Always sleep long enough for any remaining messages to complete sending
                System.Threading.Thread.Sleep(100);
            }
        }
开发者ID:Csharper1972,项目名称:Direct3DHook,代码行数:72,代码来源:EntryPoint.cs

示例6: Main

        static void Main(string[] args)
        {
            bstuff = new BotStuff();
            Donify = bstuff.OnyVariables.Donify;
            logger = bstuff.OnyVariables.logger;
            nstruct = bstuff.OnyVariables.nstruct;
            if (!File.Exists("funcpersistence.xml"))
                bstuff.OnyVariables.persistence.save();
            bstuff.OnyVariables.persistence.load();
            LoadPlugins();
            bstuff.OnyEvents.InComingMessage += new BotStuff.BotEvents.IncomingMessageHook(OnyEvents_InComingMessage);
            if (!socketfunctions.trybindsocket(mainsock, ref port, true, 50, IPAddress.Any))
            { logger.log("FAILED TO BIND TO ANY PORT. EXITTING", Logging.Priority.Critical); return; }
            logger.log("Initialized main function", Logging.Priority.Info);
            logger.log("Loading variables..",Logging.Priority.Notice);

            try
            { bstuff.OnyFunctions.PrivFunctions.loadnow(new OnyLib.SpecialClasses.BotFunctionData(nstruct)); }
            catch (Exception ex)
            { logger.logerror(ex); }
            logger.log("Trying to load playback file..", Logging.Priority.Notice);
            try { nstruct.loadplayback(); }
            catch (Exception ex) { logger.logerror(ex); }

            while (bstuff.OnyVariables.run)
            {
                if ((bstuff.OnyVariables.amountloops % 10) == 0) { nstruct.saveplayback(); bstuff.OnyVariables.amountloops = 0; bstuff.OnyVariables.persistence.save(); }
                logger.log("Waiting for incoming commands", Logging.Priority.Info);
                Donify.Reset();
                mainsock.BeginAccept(new AsyncCallback(acceptIncomingConnection), mainsock);
                Donify.WaitOne();
            }
            nstruct.saveplayback();
            bstuff.OnyVariables.persistence.save();
            Console.WriteLine("Going down!");
            logger.log("Shutting down bot.", Logging.Priority.Notice);
            logger.log("Uptime: " + (DateTime.Now - bstuff.OnyVariables.starttime).ToString(), Logging.Priority.Info);
            Environment.Exit(0);
        }
开发者ID:xarinatan,项目名称:Onymity,代码行数:39,代码来源:Program.cs

示例7: ConnectionManagerRemovesServicesNotExistingInServiceDiscovery

        public void ConnectionManagerRemovesServicesNotExistingInServiceDiscovery()
        {
            var manualResetEvent = new System.Threading.ManualResetEvent(false);
            var serviceUri1 = new ServiceUri()
            {
                Address = "jack",
                BindingType = BindingType.BasicHttpBinding
            };

            var serviceUri2 = new ServiceUri()
            {
                Address = "jackie",
                BindingType = BindingType.BasicHttpBinding
            };

            Dictionary<ServiceUri, PerformanceStatistics> services
                = new Dictionary<ServiceUri, PerformanceStatistics>()
                {
                    {serviceUri1, new PerformanceStatistics()},
                    {serviceUri2, new PerformanceStatistics()}
                };
            var serviceDiscoveryMock = new Mock<IServiceDiscovery>(MockBehavior.Strict);
            serviceDiscoveryMock.Setup(sd => sd.GetPerformanceStatistics()).Returns(() => services).Callback(() => manualResetEvent.Set());

            var manager = new ConnectionManager(remoteService: null, listener: null,
                serviceDiscovery: serviceDiscoveryMock.Object,
                serviceDiscoveryPeriod: new TimeSpan(days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds: 10));

            manualResetEvent.WaitOne();
            System.Threading.Thread.Sleep(10);
            manager.RemoteServices.Count().ShouldBe(2);
            services.Remove(serviceUri1);
            manualResetEvent.Reset();
            manualResetEvent.WaitOne();

            manager.RemoteServices.Count().ShouldBe(1);
        }
开发者ID:pbazydlo,项目名称:bluepath,代码行数:37,代码来源:ConnectionManagerTests.cs

示例8: LoadTexture

        bool LoadTexture(UUID textureID, ref Image texture, bool removeAlpha)
        {
            var gotImage = new System.Threading.ManualResetEvent(false);
            Image img = null;

            try
            {
                gotImage.Reset();
                byte[] tgaData;
                Client.Assets.RequestImage(textureID, (TextureRequestState state, AssetTexture assetTexture) =>
                {
                    ManagedImage mi;
                    if (state == TextureRequestState.Finished && OpenJPEG.DecodeToImage(assetTexture.AssetData, out mi))
                    {

                        if (removeAlpha)
                        {
                            if ((mi.Channels & ManagedImage.ImageChannels.Alpha) != 0)
                            {
                                mi.ConvertChannels(mi.Channels & ~ManagedImage.ImageChannels.Alpha);
                            }
                        }
                        tgaData = mi.ExportTGA();
                        img = LoadTGAClass.LoadTGA(new MemoryStream(tgaData));
                    }
                    gotImage.Set();
                });
                gotImage.WaitOne(30 * 1000, false);

                if (img != null)
                {
                    texture = img;
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e);
                return false;
            }
        }
开发者ID:Booser,项目名称:radegast,代码行数:42,代码来源:DAEExport.cs

示例9: CancelPendingRequests

		public void CancelPendingRequests ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			var mre = new ManualResetEvent (false);

			mh.OnSendFull = (l, c) => {
				mre.Set ();
				Assert.IsTrue (c.WaitHandle.WaitOne (1000), "#20");
				Assert.IsTrue (c.IsCancellationRequested, "#21");
				mre.Set ();
				return CompletedTask.FromResult (new HttpResponseMessage ());
			};

			var t = Task.Factory.StartNew (() => {
				client.SendAsync (request).Wait (WaitTimeout);
			});

			Assert.IsTrue (mre.WaitOne (500), "#1");
			mre.Reset ();
			client.CancelPendingRequests ();
			Assert.IsTrue (t.Wait (500), "#2");

			request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			mh.OnSendFull = (l, c) => {
				Assert.IsFalse (c.IsCancellationRequested, "#30");
				return CompletedTask.FromResult (new HttpResponseMessage ());
			};

			client.SendAsync (request).Wait (WaitTimeout);
		}
开发者ID:RainsSoft,项目名称:dotnet-httpclient35,代码行数:33,代码来源:HttpClientTest.cs

示例10: UIBlockingInvoke

        /// <summary>
        /// Runs a MethodInvoker delegate on the UI thread from whichever thread we are currently calling from and BLOCKS until it is complete
        /// </summary>
        /// <param name="ivk"></param>
        public void UIBlockingInvoke(MethodInvoker ivk)
        {
            bool result;
            System.Threading.ManualResetEvent UIAsyncComplete = new System.Threading.ManualResetEvent(false);
            UIAsyncComplete.Reset();
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(delegate()
                {
                    try
                    {
                        ivk();
                    }
                    finally
                    {
                        UIAsyncComplete.Set();
                    }
                }));

                while (AppRunning)
                {
                    //Check AppRunning...
                    //Don't call WaitOne(int32)!!!  It was added in .NET framework 2.0 SERVICE PACK 2!!
                    //Instead call WaitOne(int32, false).  This works in .NET framework 2.0 RTM.
                    result = UIAsyncComplete.WaitOne(500, false);      //timeout after 500mS to check if AppRunning is still true
                    if (result)
                    {
                        break;  //Exit when UIAsyncComplete has been set OR if AppRunning becomes false.
                    }
                }
            }
            else
            {
                ivk();
            }
        }
开发者ID:jdunne525,项目名称:AutoItXTest,代码行数:40,代码来源:frmMain.cs


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