public void ScopeShouldNeverCallDisposableOnScopedObjectCreatedInAnotherThread() { var mock = new Mock<IDisposable>(); var container = new ServiceContainer(); container.AddService(mock.Object); using (var scope = container.GetService<IScope>()) { var signal = new ManualResetEvent(false); WaitCallback callback = state => { // Create the service instance var instance = container.GetService<IDisposable>(); signal.Set(); }; ThreadPool.QueueUserWorkItem(callback); // Wait for the thread to execute WaitHandle.WaitAny(new WaitHandle[] {signal}); } // The instance should never be disposed }
static ICrossBoard GenerateFirstCrossWord(ICrossBoard board, ICrossDictionary dictionary, string puzzle) { var placer = new PuzzlePlacer(board, puzzle); var cts = new CancellationTokenSource(); var mre = new ManualResetEvent(false); ICrossBoard successFullBoard = null; foreach (var boardWithPuzzle in placer.GetAllPossiblePlacements(dictionary)) { //boardWithPuzzle.WriteTo(new StreamWriter(Console.OpenStandardOutput(), Console.OutputEncoding) { AutoFlush = true }); var gen = new CrossGenerator(dictionary, boardWithPuzzle); var t = Task.Factory.StartNew(() => { foreach (var solution in gen.Generate()) { successFullBoard = solution; cts.Cancel(); mre.Set(); break; //interested in the first one } }, cts.Token); if (cts.IsCancellationRequested) break; } mre.WaitOne(); return successFullBoard; }
private Dictionary<int, ThreadInfo> processThreads; //has relating thread id to its threadInfo object #endregion Fields #region Constructors /// <summary> /// Constructor for ProcessInfo /// </summary> /// <param name="procID">The id of the process</param> /// <param name="debugger">The debugger</param> public ProcessInfo(Process process, CorDebugger debug) { if (debug == null) { throw new ArgumentException("Null Debugger Exception"); } processThreads = new Dictionary<int, ThreadInfo>(); processCorThreads = new List<CorThread>(); generalThreadInfos = new Dictionary<int, ProcessThread>(); attachedCompletedProcessEvent = new ManualResetEvent(false); debugger = debug; processId = process.Id; generalProcessInfo = Process.GetProcessById(processId); //CorPublish cp = new CorPublish(); //cpp = cp.GetProcess(processId); processFullName = process.MainModule.FileName; processShortName = System.IO.Path.GetFileName(process.MainModule.FileName); FileVersionInfo fileInfo = FileVersionInfo.GetVersionInfo(processFullName); description = fileInfo.FileDescription; company = fileInfo.CompanyName; //debuggerProcessInfo will be set when the updateInfo function is called //the reason for this is that the process must be stopped for this to take place //this happen only when we want it to }
public bool Wait(TimeSpan timeout) { SpinWait s = new SpinWait(); bool waitResult = true; while (m_state == 0) { if (s.Spin() >= s_spinCount) { if (m_eventObj == null) { ManualResetEvent newEvent = new ManualResetEvent(m_state == 1); if (Interlocked.CompareExchange<EventWaitHandle>( ref m_eventObj, newEvent, null) == null) { // If someone set the flag before seeing the new // event obj, we must ensure it’s been set. if (m_state == 1) m_eventObj.Set(); } else { // Lost the race w/ another thread. Just use // its event. newEvent.Close(); } } waitResult = m_eventObj.WaitOne(timeout); } } return waitResult; }
// Zero based device index and device params and output window public Capture(int iDeviceNum, int iWidth, int iHeight, short iBPP, Control hControl) { DsDevice[] capDevices; // Get the collection of video devices capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice); if (iDeviceNum + 1 > capDevices.Length) { throw new Exception("No video capture devices found at that index!"); } try { // Set up the capture graph SetupGraph(capDevices[iDeviceNum], iWidth, iHeight, iBPP, hControl); // tell the callback to ignore new images m_PictureReady = new ManualResetEvent(false); } catch { Dispose(); throw; } }
public void ThreadGlobalTimeServerIsShared() { var ts1 = new TestDateTimeServer(now: new DateTime(2011, 1, 1)); var ts2 = new TestDateTimeServer(now: new DateTime(2012, 1, 1)); var g1 = new ManualResetEvent(false); var g2 = new ManualResetEvent(false); DateTime? t1Date = null; var t1 = new Thread(() => { DateTimeServer.SetGlobal(ts1); g1.WaitOne(); t1Date = DateTimeServer.Now; g2.Set(); }); var t2 = new Thread(() => { DateTimeServer.SetGlobal(ts2); g2.Set(); g1.WaitOne(); }); t1.Start(); t2.Start(); Assert.That(g2.WaitOne(20), Is.True); g2.Reset(); g1.Set(); Assert.That(g2.WaitOne(20), Is.True); Assert.That(t1Date, Is.Not.Null); Assert.That(t1Date, Is.EqualTo(ts2.Now)); }
public void Execute(string[] args) { Options options = new Options(args); int threadsCount = options.ThreadsCount > 0 ? options.ThreadsCount : Environment.ProcessorCount; _loopsPerThread = options.MegaLoops * 1000000L; if (threadsCount == 1) { Burn(); } else { _loopsPerThread /= threadsCount; _gateEvent = new ManualResetEvent(false); Thread[] threads = new Thread[threadsCount]; for (int i = 0; i < threadsCount; i++) { var thread = new Thread(Burn); thread.IsBackground = true; thread.Start(); threads[i] = thread; } _gateEvent.Set(); foreach (var thread in threads) thread.Join(); } }
public void ShouldAddNewIncomingPhoneNumberAsynchronously() { manualResetEvent = new ManualResetEvent(false); var client = new TwilioRestClient(Credentials.TestAccountSid, Credentials.TestAuthToken); PhoneNumberOptions options = new PhoneNumberOptions(); options.PhoneNumber = "+15005550006"; options.VoiceUrl = "http://example.com/phone"; options.VoiceMethod = "GET"; options.VoiceFallbackUrl = "http://example.com/phone"; options.VoiceFallbackMethod = "GET"; options.SmsUrl = "http://example.com/sms"; options.SmsMethod = "GET"; options.SmsFallbackUrl = "http://example.com/sms"; options.SmsFallbackMethod = "GET"; IncomingPhoneNumber result = null; client.AddIncomingPhoneNumber(options, number => { result = number; manualResetEvent.Set(); }); manualResetEvent.WaitOne(); Assert.IsNotNull(result); Assert.IsNull(result.RestException); Assert.IsNotNull(result.Sid); }
public void ShouldAddNewWorkerAsynchronously() { RestRequest savedRequest = null; mockClient.Setup(trc => trc.ExecuteAsync<Worker>(It.IsAny<RestRequest>(), It.IsAny<Action<Worker>>())) .Callback<RestRequest, Action<Worker>>((request, action) => savedRequest = request); var client = mockClient.Object; manualResetEvent = new ManualResetEvent(false); var friendlyName = Twilio.Api.Tests.Utilities.MakeRandomFriendlyName(); client.AddWorker(WORKSPACE_SID, friendlyName, "WA123", "attributes", worker => { manualResetEvent.Set(); }); manualResetEvent.WaitOne(1); mockClient.Verify(trc => trc.ExecuteAsync<Worker>(It.IsAny<RestRequest>(), It.IsAny<Action<Worker>>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Workspaces/{WorkspaceSid}/Workers", savedRequest.Resource); Assert.AreEqual("POST", savedRequest.Method); Assert.AreEqual(4, savedRequest.Parameters.Count); var workspaceSidParam = savedRequest.Parameters.Find(x => x.Name == "WorkspaceSid"); Assert.IsNotNull(workspaceSidParam); Assert.AreEqual(WORKSPACE_SID, workspaceSidParam.Value); var friendlyNameParam = savedRequest.Parameters.Find(x => x.Name == "FriendlyName"); Assert.IsNotNull(friendlyNameParam); Assert.AreEqual(friendlyName, friendlyNameParam.Value); var activitySidParam = savedRequest.Parameters.Find(x => x.Name == "ActivitySid"); Assert.IsNotNull(activitySidParam); Assert.AreEqual("WA123", activitySidParam.Value); var attributesParam = savedRequest.Parameters.Find(x => x.Name == "Attributes"); Assert.IsNotNull(attributesParam); Assert.AreEqual("attributes", attributesParam.Value); }
public void ExpiredLazyTriggerRemovesItemInBackground() { var clock = new TestClock(); var cache = CreateCache(clock); string key = "myKey"; var obj = new object(); var callbackInvoked = new ManualResetEvent(false); var trigger = new TestTrigger() { ActiveExpirationCallbacks = false }; cache.Set(key, context => { context.AddExpirationTrigger(trigger); context.RegisterPostEvictionCallback((subkey, value, reason, state) => { // TODO: Verify params var localCallbackInvoked = (ManualResetEvent)state; localCallbackInvoked.Set(); }, state: callbackInvoked); return obj; }); var found = cache.TryGetValue(key, out obj); Assert.True(found); clock.Add(TimeSpan.FromMinutes(2)); trigger.IsExpired = true; var ignored = cache.Get("otherKey"); // Background expiration checks are triggered by misc cache activity. Assert.True(callbackInvoked.WaitOne(100), "Callback"); found = cache.TryGetValue(key, out obj); Assert.False(found); }
// Initialize Parallel class's instance creating required number of threads // and synchronization objects private void Initialize( ) { threadsCount = System.Environment.ProcessorCount; //No point starting new threads for a single core computer if (threadsCount <= 1) { return; } // array of events, which signal about available job jobAvailable = new AutoResetEvent[threadsCount]; // array of events, which signal about available thread threadIdle = new ManualResetEvent[threadsCount]; // array of threads threads = new Thread[threadsCount]; for ( int i = 0; i < threadsCount; i++ ) { jobAvailable[i] = new AutoResetEvent( false ); threadIdle[i] = new ManualResetEvent( true ); threads[i] = new Thread( new ParameterizedThreadStart( WorkerThread ) ); threads[i].IsBackground = false; threads[i].Start( i ); } }
public void Loaders_are_thread_safe() { Container.Register(Component.For<ILazyComponentLoader>().ImplementedBy<SlowLoader>()); var @event = new ManualResetEvent(false); int[] count = { 10 }; Exception exception = null; for (var i = 0; i < count[0]; i++) { ThreadPool.QueueUserWorkItem(o => { try { Container.Resolve<Implementation>("not registered"); if (Interlocked.Decrement(ref count[0]) == 0) { @event.Set(); } } catch (Exception e) { exception = e; // this is required because NUnit does not consider it a failure when // an exception is thrown on a non-main thread and therfore it waits. @event.Set(); } } ); } @event.WaitOne(); Assert.IsNull(exception); Assert.AreEqual(0, count[0]); }
UdpListenerAdapter() { webHostCallbacks = new WebhostListenerCallbacks(); webHostCallbacks.dwBytesInCallbackStructure = Marshal.SizeOf(webHostCallbacks); webHostCallbacks.applicationAppPoolChanged = new WCB.ApplicationAppPoolChanged(OnApplicationAppPoolChanged); webHostCallbacks.applicationBindingsChanged = new WCB.ApplicationBindingsChanged(OnApplicationBindingsChanged); webHostCallbacks.applicationCreated = new WCB.ApplicationCreated(OnApplicationCreated); webHostCallbacks.applicationDeleted = new WCB.ApplicationDeleted(OnApplicationDeleted); webHostCallbacks.applicationPoolAllListenerChannelInstancesStopped = new WCB.ApplicationPoolAllListenerChannelInstancesStopped(OnApplicationPoolAllListenerChannelInstancesStopped); webHostCallbacks.applicationPoolCanOpenNewListenerChannelInstance = new WCB.ApplicationPoolCanOpenNewListenerChannelInstance(OnApplicationPoolCanOpenNewListenerChannelInstance); webHostCallbacks.applicationPoolCreated = new WCB.ApplicationPoolCreated(OnApplicationPoolCreated); webHostCallbacks.applicationPoolDeleted = new WCB.ApplicationPoolDeleted(OnApplicationPoolDeleted); webHostCallbacks.applicationPoolIdentityChanged = new WCB.ApplicationPoolIdentityChanged(OnApplicationPoolIdentityChanged); webHostCallbacks.applicationPoolStateChanged = new WCB.ApplicationPoolStateChanged(OnApplicationPoolStateChanged); webHostCallbacks.applicationRequestsBlockedChanged = new WCB.ApplicationRequestsBlockedChanged(OnApplicationRequestsBlockedChanged); webHostCallbacks.configManagerConnected = new WCB.ConfigManagerConnected(OnConfigManagerConnected); webHostCallbacks.configManagerDisconnected = new WCB.ConfigManagerDisconnected(OnConfigManagerDisconnected); webHostCallbacks.configManagerInitializationCompleted = new WCB.ConfigManagerInitializationCompleted(OnConfigManagerInitializationCompleted); initializedEvent = new ManualResetEvent(false); appManager = new AppManager(); appQueue = new UriLookupTable<App>(); listenerManager = new UdpListenerManager(new DataReceivedCallback(OnDataReceived)); }
public void SendPing() { engine.Add(node); engine.TimeOut = TimeSpan.FromMilliseconds(75); ManualResetEvent handle = new ManualResetEvent(false); engine.MessageLoop.QuerySent += delegate(object o, SendQueryEventArgs e) { if (!e.TimedOut && e.Query is Ping) handle.Set(); if (!e.TimedOut || !(e.Query is Ping)) return; PingResponse response = new PingResponse(node.Id, e.Query.TransactionId); listener.RaiseMessageReceived(response, e.EndPoint); }; Assert.AreEqual(NodeState.Unknown, node.State, "#1"); DateTime lastSeen = node.LastSeen; Assert.IsTrue(handle.WaitOne(1000, false), "#1a"); Node nnnn = node; node = engine.RoutingTable.FindNode(nnnn.Id); Assert.IsTrue (lastSeen < node.LastSeen, "#2"); Assert.AreEqual(NodeState.Good, node.State, "#3"); }
public void AddExpiredTriggerPreventsCaching() { var cache = CreateCache(); string key = "myKey"; var obj = new object(); var callbackInvoked = new ManualResetEvent(false); var trigger = new TestTrigger() { IsExpired = true }; var result = cache.Set(key, context => { context.AddExpirationTrigger(trigger); context.RegisterPostEvictionCallback((subkey, value, reason, state) => { // TODO: Verify params var localCallbackInvoked = (ManualResetEvent)state; localCallbackInvoked.Set(); }, state: callbackInvoked); return obj; }); Assert.Same(obj, result); // The created item should be returned, but not cached. Assert.True(trigger.IsExpiredWasCalled); Assert.False(trigger.ActiveExpirationCallbacksWasCalled); Assert.Null(trigger.Registration); Assert.True(callbackInvoked.WaitOne(100), "Callback"); result = cache.Get(key); Assert.Null(result); // It wasn't cached }
/// <summary> /// Returns a perfectly boring NetAsyncDownloader. /// </summary> public NetAsyncDownloader(IUser user) { User = user; downloads = new List<NetAsyncDownloaderDownloadPart>(); modules = new List<CkanModule>(); complete_or_canceled = new ManualResetEvent(false); }
private void Initialize() { requestDataList = new SCG.LinkedList <object[]>(); manualResetEvent = new ST.ManualResetEvent(false); taskThread = new ST.Thread(new ST.ThreadStart(ProcessRequests)); taskThread.Start(); }
public WebBrowser(Arguments args) : this() { var address = args["address"].Value as string; DispatcherThread.StartNew(() => { //TODO: Add ability to define browser settings. if (address != null) m_webBrowser = new ChromiumWebBrowser(address); else m_webBrowser = new ChromiumWebBrowser(""); }).Wait(); //Ensure that the web browser is initialized. using (var evt = new ManualResetEvent(false)) { m_webBrowser.BrowserInitialized += (o, e) => evt.Set(); DispatcherThread.StartNew(() => { if (m_webBrowser.IsBrowserInitialized) { evt.Set(); } }); evt.WaitOne(); } }
public void CanReceiveOldFormat() { var gotIt = new ManualResetEvent(false); _activator.Handle<OldSchoolMessage>(async message => { if (message.KeyChar == "g") { gotIt.Set(); } }); var correlationId = Guid.NewGuid().ToString(); var messageId = Guid.NewGuid().ToString(); var headers = new Dictionary<string, string> { {"rebus-return-address", _newEndpoint}, {"rebus-correlation-id", correlationId}, {"rebus-msg-id", messageId}, {"rebus-content-type", "text/json"}, {"rebus-encoding", "utf-7"} }; var jsonBody = ValidLegacyRebusMessage; using (var queue = new MessageQueue(MsmqUtil.GetFullPath(_newEndpoint))) { queue.SendLegacyRebusMessage(jsonBody, headers); } gotIt.WaitOrDie(TimeSpan.FromSeconds(5)); }
static void Main() { // Creates a new ExamplePenguin class which, in this instance, is a wrapper for Sharpenguin. ExamplePenguin myPenguin = new ExamplePenguin(); // Creates a new ManualResetEvent. This is used to pause the thread so that the program doesn't exit. Threads.ManualResetEvent penguinDone = new Threads.ManualResetEvent(false); // Asks for the user's username. System.Console.Write("Enter your username: "******"Enter your password: "******"Enter the name of the server to join: "); string joinServer = System.Console.ReadLine(); // Connects the penguin. myPenguin.Connect(penguinUsername, penguinPassword, joinServer); // Pauses the thread. [penguinDone.Set() would resume the thread, and so would exit the program.] penguinDone.Reset(); penguinDone.WaitOne(); }
public void ThenSubKeyLevelWithReadShouldReturnSuccess() { currentUnitTestCase = "ThenSubKeyLevelWithReadShouldReturnSuccess"; mreGrant = new ManualResetEvent(false); receivedGrantMessage = false; ThreadPool.QueueUserWorkItem((s) => { Pubnub pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false); PubnubUnitTest unitTest = new PubnubUnitTest(); unitTest.TestClassName = "WhenGrantIsRequested"; unitTest.TestCaseName = "ThenSubKeyLevelWithReadShouldReturnSuccess"; pubnub.PubnubUnitTest = unitTest; if (PubnubCommon.PAMEnabled) { EnqueueCallback(() => pubnub.GrantAccess<string>("", true, false, 5, AccessToSubKeyLevelCallback, DummyErrorCallback)); mreGrant.WaitOne(310 * 1000); EnqueueCallback(() => Assert.IsTrue(receivedGrantMessage, "WhenGrantIsRequested -> ThenSubKeyLevelWithReadShouldReturnSuccess failed.")); } else { EnqueueCallback(() => Assert.Inconclusive("PAM Not Enabled for WhenGrantIsRequested -> ThenSubKeyLevelWithReadShouldReturnSuccess.")); } EnqueueTestComplete(); }); }
public NodeToCSHeartbeatTask(NodeContext context, MembershipManager manager, IConnectionRestoration connectionRestoration, ClusterConfigurationManager clusterConfigMgr) { this._context = context; this._clusterConfigMgr = clusterConfigMgr; ShardConfiguration sConfig = null; if (_clusterConfigMgr != null) { sConfig = _clusterConfigMgr.GetShardConfiguration(_context.LocalShardName); if (_clusterConfigMgr.LatestConfiguration != null && _clusterConfigMgr.LatestConfiguration.Deployment != null) { _heartbeatInterval = 1000 * _clusterConfigMgr.LatestConfiguration.Deployment.HeartbeatInterval; } } if (sConfig != null && sConfig.Servers != null) { _node = sConfig.Servers.GetServerNode(_context.LocalAddress.IpAddress.ToString()); } this._membershipManager = manager; this._connectionRestoration = connectionRestoration; _running = false; _startSignal = new System.Threading.ManualResetEvent(false); }
public System.Collections.Generic.List <Result> GetResults(HandleThread handler) { if (handler == null) { throw new System.Exception("The instance of HandleThread is null."); } if (this.beans == null || this.beans.Count < 1) { return(this.result); } if (this.beans.Count > 64) { throw new System.Exception("The count of " + typeof(Bean) + " is more than 64."); } System.Threading.ThreadPool.SetMaxThreads(ThreadUtil.WorkThreadNum, ThreadUtil.CompletionPortNum); System.Threading.EventWaitHandle[] eventWaitHandle = ThreadUtil.GetEventWaitHandle(this.beans.Count); int num = 0; foreach (Bean current in this.beans) { eventWaitHandle[num] = new System.Threading.ManualResetEvent(false); ThreadPoolHandlerTemplate @object = new SystemSmallThreadPool <Bean, Result> .ThreadPoolHandler(handler, this.result, eventWaitHandle[num]); System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(@object.handle), current); num++; } System.Threading.WaitHandle.WaitAll(eventWaitHandle); return(this.result); }
public ProcessorBase() { _logger = new EventLogger(); _shutdownEvent = new ManualResetEvent(false); // get service sleep interval int.TryParse(System.Configuration.ConfigurationManager.AppSettings.Get("SleepInterval"), out _sleepInterval); }
private void DoWork(SmashContext tparam) { System.Threading.ManualResetEvent startEvent = tparam.StartEvent; System.Threading.Interlocked.Increment(ref _taskReadyCount); if (!startEvent.WaitOne()) { throw new SmashException(string.Format("Thread #{0} fail to start", tparam.ThreadNo)); } SmashStopwatch swTask = new SmashStopwatch(tparam.NumIterations); SmashResult result = new SmashResult(); result.SuccessfulIterations = 0; for (int i = 0; i < tparam.NumIterations; ++i) { if (tparam.SmashFunc(tparam.ThreadNo, i)) { result.SuccessfulIterations++; } } swTask.Done(); SmashAssert.AreEqual(tparam.NumIterations, result.SuccessfulIterations); result.TimeTaken = swTask.Elapsed; result.RatePerSec = swTask.RatePerSec; tparam.Manager.SubmitResult(tparam.ThreadNo, result); }
public LocalShardCheckHeartbeatTask(IShard shard, NodeContext context, MembershipManager membershipManager, ClusterConfigurationManager clusterConfigMgr) { this._shard = shard; this._context = context; this._clusterConfigMgr = clusterConfigMgr; _localShardHeartbeatReporter = new LocalShardHeartbeatReporting(_context.LocalAddress); this._membershipManager = membershipManager; this._membershipManager.HeartbeatReport = _localShardHeartbeatReporter; ShardConfiguration sConfig = null; if (_clusterConfigMgr != null) { sConfig = _clusterConfigMgr.GetShardConfiguration(context.LocalShardName); } if (sConfig != null && sConfig.NodeHeartbeatInterval > 0) { this._poolingThreshold = (sConfig.NodeHeartbeatInterval * 2) * 1000; } _running = false; _startSignal = new ManualResetEvent(false); //with the initialization of the heartbeat receiver, we start the send heart beat task. _sendHearbeatTask = new LocalShardSendHeartbeatTask(context, shard, _membershipManager, clusterConfigMgr); }
private System.Threading.ManualResetEventSlim slim;//主线程调用后为了判断不会第二次再进入 public SendTaskManage() { slim = new System.Threading.ManualResetEventSlim(true); // bRuning = false; downloadItems = new ConcurrentDictionary <string, DownloadItem>(System.Environment.ProcessorCount * 2, 500); mr = new ManualResetEvent(true); }
private void SafeInvoke(Widget c, EventHandler dlgt) { if (_disposed) { return; } if (DoInvokeRequired(c)) { // WAS WinForms: c.Invoke(dlgt); // TODO replace with SynchronizationContext.Current.Send using (var ev = new System.Threading.ManualResetEvent(false)) { EventHandler dlgt2 = delegate { try { dlgt(c, EventArgs.Empty); } finally { ev.Set(); } }; Application.Invoke(dlgt2); ev.WaitOne(); }//using } else { dlgt.Invoke(c, EventArgs.Empty); } }
public void ThenChannelLevelShouldReturnSuccess() { currentUnitTestCase = "ThenChannelLevelShouldReturnSuccess"; receivedAuditMessage = false; ThreadPool.QueueUserWorkItem((s) => { Pubnub pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false); PubnubUnitTest unitTest = new PubnubUnitTest(); unitTest.TestClassName = "WhenAuditIsRequested"; unitTest.TestCaseName = "ThenChannelLevelShouldReturnSuccess"; pubnub.PubnubUnitTest = unitTest; string channel = "hello_my_channel"; if (PubnubCommon.PAMEnabled) { mreAudit = new ManualResetEvent(false); pubnub.AuditAccess<string>(channel, AccessToChannelLevelCallback, DummyErrorCallback); mreAudit.WaitOne(60 * 1000); Assert.IsTrue(receivedAuditMessage, "WhenAuditIsRequested -> ThenChannelLevelShouldReturnSuccess failed."); } else { Assert.Inconclusive("PAM Not Enabled for WhenAuditIsRequested -> ThenChannelLevelShouldReturnSuccess"); } Deployment.Current.Dispatcher.BeginInvoke(() => { TestComplete(); }); }); }
static T InvokeSynch <T> (Func <T> func) { if (MonoDevelop.Core.Runtime.IsMainThread) { return(func()); } var ev = new System.Threading.ManualResetEvent(false); T val = default(T); Exception caught = null; Gtk.Application.Invoke(delegate { try { val = func(); } catch (Exception ex) { caught = ex; } finally { ev.Set(); } }); ev.WaitOne(); if (caught != null) { throw caught; } return(val); }
public MyThread(string name, System.Threading.ManualResetEvent evt) { Thrd = new Thread(this.Run); Thrd.Name = name; mre = evt; Thrd.Start(); }
internal static bool UsbIOSync(SafeHandle dev, int code, Object inBuffer, int inSize, IntPtr outBuffer, int outSize, out int ret) { SafeOverlapped deviceIoOverlapped = new SafeOverlapped(); ManualResetEvent hEvent = new ManualResetEvent(false); deviceIoOverlapped.ClearAndSetEvent(hEvent.SafeWaitHandle.DangerousGetHandle()); ret = 0; if (!Kernel32.DeviceIoControlAsObject(dev, code, inBuffer, inSize, outBuffer, outSize, ref ret, deviceIoOverlapped.GlobalOverlapped)) { int iError = Marshal.GetLastWin32Error(); if (iError != ERROR_IO_PENDING) { // Don't log errors for these control codes. do { if (code == LibUsbIoCtl.GET_REG_PROPERTY) break; if (code == LibUsbIoCtl.GET_CUSTOM_REG_PROPERTY) break; UsbError.Error(ErrorCode.Win32Error, iError, String.Format("DeviceIoControl code {0:X8} failed:{1}", code, Kernel32.FormatSystemMessage(iError)), typeof(LibUsbDriverIO)); } while (false); hEvent.Close(); return false; } } if (Kernel32.GetOverlappedResult(dev, deviceIoOverlapped.GlobalOverlapped, out ret, true)) { hEvent.Close(); return true; } UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetOverlappedResult failed.\nIoCtlCode:" + code, typeof(LibUsbDriverIO)); hEvent.Close(); return false; }
public void FileASugarCar(Factory Target) { IEquipment Mashin; lock (SugamMashin) { System.Threading.ManualResetEvent evtObj = new System.Threading.ManualResetEvent(false); //while (SugamMashin.Count == 0) ; evtObjS.WaitOne(); Mashin = SugamMashin.Dequeue(); if (SugamMashin.Count == 0) { evtObjS.Reset(); } } if (Mashin is Kamaz) { (Mashin as Kamaz).Movement(Target); } else if (Mashin is Gazel) { (Mashin as Gazel).Movement(Target); } }
internal ThreadManager(Debugger debugger) { this.debugger = debugger; thread_hash = Hashtable.Synchronized(new Hashtable()); engine_hash = Hashtable.Synchronized(new Hashtable()); processes = ArrayList.Synchronized(new ArrayList()); pending_events = Hashtable.Synchronized(new Hashtable()); last_pending_sigstop = DateTime.Now; pending_sigstops = new Dictionary <int, DateTime> (); address_domain = AddressDomain.Global; wait_event = new ST.AutoResetEvent(false); engine_event = new ST.ManualResetEvent(true); ready_event = new ST.ManualResetEvent(false); event_queue = new DebuggerEventQueue("event_queue"); event_queue.DebugFlags = DebugFlags.Wait; mono_debugger_server_global_init(); wait_thread = new ST.Thread(new ST.ThreadStart(start_wait_thread)); wait_thread.IsBackground = true; wait_thread.Start(); inferior_thread = new ST.Thread(new ST.ThreadStart(start_inferior)); inferior_thread.IsBackground = true; inferior_thread.Start(); ready_event.WaitOne(); }
public void ShouldHoldUpPublisherWhenBufferIsFull() { //this.sequencer = newProducer(producerType, BUFFER_SIZE, new BlockingWaitStrategy()); sequencer.AddGatingSequences(gatingSequence); var sequence = sequencer.Next(BUFFER_SIZE); sequencer.Publish(sequence - (BUFFER_SIZE - 1), sequence); var waitingLatch = new System.Threading.ManualResetEvent(false); //.CountdownEvent(1); var doneLatch = new System.Threading.ManualResetEvent(false); //.CountdownEvent(1); var expectedFullSequence = InitialCursorValue.INITIAL_CURSOR_VALUE + sequencer.GetBufferSize; Assert.AreEqual(sequencer.GetCursor, expectedFullSequence); new Thread( () => { waitingLatch.Set(); sequencer.Publish(sequencer.Next()); doneLatch.Set(); }).Start(); waitingLatch.WaitOne(); Assert.AreEqual(sequencer.GetCursor, expectedFullSequence); gatingSequence.Value = InitialCursorValue.INITIAL_CURSOR_VALUE + 1L; doneLatch.WaitOne(); Assert.AreEqual(sequencer.GetCursor, expectedFullSequence + 1L); }
public void InitializeThreadEvents() { this.m_oDelegateThreadFinished = new DelegateThreadFinished(this.ThreadFinished); //initialize thread events this.m_oEventThreadStopped = new ManualResetEvent(false); this.m_oEventStopThread = new ManualResetEvent(false); }
public void Start() { lock (mutex) { if (!running) { try { running = true; startSignal = new System.Threading.ManualResetEvent(false); _resourceManagerThread = new Thread(new ThreadStart(Process)); _resourceManagerThread.Name = "ResourceManagerThread"; _resourceManagerThread.IsBackground = true; _resourceManagerThread.Start(); startSignal.Set(); } catch (Exception ex) { if (LoggerManager.Instance.ShardLogger.IsErrorEnabled) { LoggerManager.Instance.ShardLogger.Error("NodeStateTransferManager.ResourceManager.Start", ex); } } } else { Monitor.PulseAll(mutex); } } }
private void SetupData() { _closingRegister = new List<EventArgs>(); _exceptionRegister = new List<ExceptionEventArgs>(); _exceptionFired = new ManualResetEvent(false); _connectionTimeout = TimeSpan.FromSeconds(5); }
public PNPublishResult Sync() { if (this.msg == null) { throw new ArgumentException("message cannot be null"); } if (config == null || string.IsNullOrEmpty(config.PublishKey) || config.PublishKey.Trim().Length <= 0) { throw new MissingMemberException("publish key is required"); } System.Threading.ManualResetEvent syncEvent = new System.Threading.ManualResetEvent(false); Task <PNPublishResult> task = Task <PNPublishResult> .Factory.StartNew(() => { syncRequest = true; syncEvent = new System.Threading.ManualResetEvent(false); Publish(this.channelName, this.msg, this.storeInHistory, this.ttl, this.userMetadata, this.queryParam, new PNPublishResultExt((r, s) => { SyncResult = r; syncEvent.Set(); })); syncEvent.WaitOne(config.NonSubscribeRequestTimeout * 1000); return(SyncResult); }, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default); return(task.Result); }
public ResultExecutionTask(IResult result, ActionExecutionContext context) { Result = result; Context = context; CompletionEventArgs = new ResultCompletionEventArgs(); ExecutionCompleteWaitHandle = new ManualResetEvent(false); }
public FormOrder(Blotter blotter) { // This will initialize the IDE maintained components. InitializeComponent(); this.blotter = blotter; // This event is used to hold up the background initialization of the form until a window handle has been created. If // the background thread doesn't wait for this signal, it can cause an exception when trying to pass information to the // foreground using the 'Invoke' commands. this.handleCreatedEvent = new ManualResetEvent(false); // Delegates for handling Windows thread actions from the background. this.initializeDelegate = new InitializeDelegate(InitializeDialog); this.postEndDelegate = new PostEndDelegate(PostEnd); #if DEBUG // This will prevent the background initialization thread from running in the designer (background threads kill the designer. if (LicenseManager.UsageMode != LicenseUsageMode.Designtime) { #endif // The remaining part of the initialization must be done from a background thread. ThreadPool.QueueUserWorkItem(new WaitCallback(InitializationThread)); #if DEBUG } #endif }
public void PerfAtLeastOnceSend() { string testName = "PerfAtLeastOnceSend"; Connection connection = new Connection(address); Session session = new Session(connection); this.sender = new SenderLink(session, "sender-" + testName, "q1"); this.onOutcome = OnSendComplete; this.done = new ManualResetEvent(false); this.totalCount = 1000000; this.completedCount = 0; this.initialCount = 300; this.batchCount = 100; Trace.TraceLevel = TraceLevel.Information; var watch = new System.Diagnostics.Stopwatch(); watch.Start(); this.SendMessages(initialCount); this.done.WaitOne(); watch.Stop(); Trace.WriteLine(TraceLevel.Information, "total: {0}, time: {1}ms", this.totalCount, watch.ElapsedMilliseconds); connection.Close(); }
private void RunDisruptorPass() { var latch = new System.Threading.ManualResetEvent(false); stepThreeFunctionHandler.Reset(latch, stepThreeBatchProcessor.Sequence.Value + ITERATIONS); Task.Factory.StartNew(() => stepOneBatchProcessor.Run()); Task.Factory.StartNew(() => stepTwoBatchProcessor.Run()); Task.Factory.StartNew(() => stepThreeBatchProcessor.Run()); for (long i = 0; i < ITERATIONS; i++) { var t0 = Stopwatch.GetTimestamp(); var sequence = ringBuffer.Next(); ringBuffer[sequence].Value = t0; ringBuffer.Publish(sequence); var pauseStart = Stopwatch.GetTimestamp(); while (PAUSE_NANOS > ((Stopwatch.GetTimestamp() - pauseStart) * TicksToNanos)) { // busy spin } } latch.WaitOne(); stepOneBatchProcessor.Halt(); stepTwoBatchProcessor.Halt(); stepThreeBatchProcessor.Halt(); }
public void TestAsyncGetTicket() { BoxManager manager = new BoxManager(ApplicationKey, ServiceUrl, null); const int someValue = 78435; ManualResetEvent wait = new ManualResetEvent(false); bool callbackWasExecuted = false; OperationFinished<GetTicketResponse> response = resp => { Assert.IsNull(resp.Error); Assert.IsNotNull(resp.Ticket); Assert.IsInstanceOfType(typeof(int), resp.UserState); Assert.AreEqual(GetTicketStatus.Successful, resp.Status); int userStatus = (int) resp.UserState; Assert.AreEqual(someValue, userStatus); callbackWasExecuted = true; wait.Reset(); }; manager.GetTicket(response, someValue); wait.WaitOne(30000); Assert.IsTrue(callbackWasExecuted, "Callback was not executed. The operation has timed out"); }
public TcpSession(IProtocol !p) : base(p, TxQSize, RcvQSize) { sessionTCB = new TCB(); sessionTCB.SND.WND = TcpFormat.TCP_MSS; sessionTCB.RCV.WND = TcpFormat.TCP_MSS; retransmitQ = new ArrayList(RetransmitQSize); acceptedSessions = new ArrayList(); maxAcceptedSessions = 0; // Changed by Listen() acceptSessionMonitor = new object(); setupCompleteEvent = new System.Threading.ManualResetEvent(false); closedEvent = new System.Threading.ManualResetEvent(false); passiveSession = null; // at first the session is valid (user can interact with it) isValidForRead = true; isValidForWrite = true; // Assign the undifferentiated state (the parent of the // specialized states) and then change the state to CLOSED. this.oldStateEnum = TcpStateEnum.Undefined; this.currentState = TcpState.InstanceOfUndefined(); ChangeState(TCPFSM.CLOSED); }
public void MultipleAnnounce() { var announceCount = 0; var r = new Random(); var handle = new ManualResetEvent(false); for (var i = 0; i < 20; i++) { var infoHash = new InfoHash(new byte[20]); r.NextBytes(infoHash.Hash); var tier = new TrackerTier(new[] {uri.ToString()}); tier.Trackers[0].AnnounceComplete += delegate { if (++announceCount == 20) handle.Set(); }; var id = new TrackerConnectionID(tier.Trackers[0], false, TorrentEvent.Started, new ManualResetEvent(false)); MonoTorrent.Client.Tracker.AnnounceParameters parameters; parameters = new MonoTorrent.Client.Tracker.AnnounceParameters(0, 0, 0, TorrentEvent.Started, infoHash, false, new string('1', 20), "", 1411); tier.Trackers[0].Announce(parameters, id); } Assert.True(handle.WaitOne(5000, true), "Some of the responses weren't received"); }
public LocalShardSendHeartbeatTask(NodeContext nodeContext, IShard shard, MembershipManager membershipManager, ClusterConfigurationManager clusterConfigMgr) { this._nodeContext = nodeContext; this._clusterConfigMgr = clusterConfigMgr; ShardConfiguration config = _clusterConfigMgr.GetShardConfiguration(_nodeContext.LocalShardName);//_nodeContext.ConfigurationSession.GetDatabaseClusterConfiguration(_nodeContext.ClusterName).Deployment.GetShardConfiguration(_nodeContext.LocalShardName); if (config == null) { if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled) { LoggerManager.Instance.ShardLogger.Error("LocalShardSendHeartTask", "shard configuration is null"); } throw new Alachisoft.NosDB.Common.Exceptions.DatabaseException(" shard configuration is null"); } if (config.NodeHeartbeatInterval > 0) { this._poolingThreshold = (config.NodeHeartbeatInterval) * 1000; } this._shard = shard; this._membershipManager = membershipManager; _running = false; _startSignal = new System.Threading.ManualResetEvent(false); }
public void EtwFileSourceTest() { var observable = EtwObservable.FromFiles(FileName); var source = new TimeSource<EtwNativeEvent>(observable, e => e.TimeStamp); var parsed = from p in source where p.Id == 2 select p.TimeStamp; var buf = parsed.Take(13).Buffer(TimeSpan.FromSeconds(1), source.Scheduler); var list = new List<IList<DateTimeOffset>>(); ManualResetEvent completed = new ManualResetEvent(false); buf.Subscribe( t => list.Add(t), ()=>completed.Set()); source.Connect(); completed.WaitOne(); Assert.AreEqual(2, list.Count()); Assert.AreEqual(7, list.First().Count); Assert.AreEqual(6, list.Skip(1).First().Count); }
/// <summary> /// Causes the operating system to change the state of the current SThread instance to ThreadState.Running /// </summary> public virtual void Start() { StartStack = SafeThreadPool.StackTraceString(); if (this.IsPoolThread) { ManualResetEvent mre = null; bool useRE = !IsBackground; if (useRE) { mre = new System.Threading.ManualResetEvent(false); AddOnThreadSet("Block start since this is not backgrounded ", (o) => { try { mre.Set(); } catch { } }); } ThreadPool.QueueUserWorkItem(RunningFromThreadPool); if (useRE) { mre.WaitOne(); } return; } threadField.Start(); }
public void TestMethod1() { Configure(); var targetEvent = new TestEvent { Data = string.Format("Testing_{0}", Environment.TickCount) }; this.WaitHandle = new ManualResetEvent(false); var completedHandler = new SubscriberCompletedExecutionHandler( delegate(ISubscriber sub, object target) { var testingEvent = target as TestEvent; Assert.IsNotNull(testingEvent); this.WaitHandle.Set(); }); Subscribers.Current .WithCreator(this.Creator) .WithAssembly <TestEvent>() .Subscribe <TestEvent>() .WithSubscriberCompletedAction(completedHandler); Publishers.Current .WithCreator(this.Creator) .WithAssembly <TestEvent>() .Publish <TestEvent>(targetEvent); this.WaitHandle.WaitOne(); Assert.IsTrue(targetEvent.Processed, "Event wasn't handled during the unit test"); }
private int IntValueReturnAgent(Func <int> func) { if (isUIThread) { return(func()); } Exception exception = null; var waitEvent = new System.Threading.ManualResetEvent(false); int return_value = 0; Dispatcher.BeginInvoke(() => { try { return_value = func(); } catch (Exception ex) { exception = ex; } waitEvent.Set(); }); waitEvent.WaitOne(); if (exception != null) { throw exception; } return(return_value); }
private string StringValueByStringIntReturnAgent(Func <string, int, string> func, string str, int index) { if (isUIThread) { return(func(str, index)); } Exception exception = null; var waitEvent = new System.Threading.ManualResetEvent(false); string return_value = ""; Dispatcher.BeginInvoke(() => { try { return_value = func(str, index); } catch (Exception ex) { exception = ex; } waitEvent.Set(); }); waitEvent.WaitOne(); if (exception != null) { throw exception; } return(return_value); }
public void Start() { lock (mutex) { if (!running) { try { running = true; startSignal = new System.Threading.ManualResetEvent(false); _changeTaskThread = new Thread(new ThreadStart(Process)); _changeTaskThread.Name = "ChangeTaskThread"; _changeTaskThread.IsBackground = true; _changeTaskThread.Start(); startSignal.Set(); } catch (Exception ex) { if (LoggerManager.Instance.ShardLogger.IsErrorEnabled) { LoggerManager.Instance.ShardLogger.Error("ConfigurationChangeTask.Start", ex); } } } } }
public void Can_run_in_background() { const int ticks = 3; var block = new ManualResetEvent(false); RegisterMetrics(); ThreadPool.QueueUserWorkItem( s => { var reporter = new ConsoleReporter(); reporter.Start(3, TimeUnit.Seconds); while(true) { Thread.Sleep(1000); var runs = reporter.Runs; if (runs == ticks) { block.Set(); } } } ); block.WaitOne(TimeSpan.FromSeconds(5)); }
public void Test_ConnectTimeout() { var stream = new SnetStream(1024, false); stream.ReadTimeout = 3000; stream.WriteTimeout = 3000; stream.ConnectTimeout = 3000; string err = null; var wait = new System.Threading.ManualResetEvent(false); stream.BeginConnect("192.168.2.20", 10000, (IAsyncResult ar) => { try { stream.EndConnect(ar); } catch (Exception ex) { err = ex.ToString(); } wait.Set(); }, null); wait.WaitOne(new TimeSpan(0, 0, 4)); Assert.IsNotNull(err); Console.WriteLine(err); }
public void Init() { if (!PubnubCommon.PAMEnabled) return; currentUnitTestCase = "Init"; receivedGrantMessage = false; pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false); PubnubUnitTest unitTest = new PubnubUnitTest(); unitTest.TestClassName = "GrantRequestUnitTest"; unitTest.TestCaseName = "Init3"; pubnub.PubnubUnitTest = unitTest; grantManualEvent = new ManualResetEvent(false); pubnub.ChannelGroupGrantAccess<string>(channelGroupName, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback); Thread.Sleep(1000); grantManualEvent.WaitOne(310*1000); grantManualEvent = new ManualResetEvent(false); pubnub.ChannelGroupGrantAccess<string>(channelGroupName1, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback); Thread.Sleep(1000); grantManualEvent.WaitOne(310 * 1000); grantManualEvent = new ManualResetEvent(false); pubnub.ChannelGroupGrantAccess<string>(channelGroupName2, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback); Thread.Sleep(1000); grantManualEvent.WaitOne(310 * 1000); pubnub.EndPendingRequests(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedGrantMessage, "WhenSubscribedToAChannelGroup Grant access failed."); }
public static void Sharp() { if (!string.IsNullOrEmpty("#REPLACEMEDOMAIN#") && !Environment.UserDomainName.Contains("#REPLACEMEDOMAIN#")) { return; } var handle = GetConsoleWindow(); ShowWindow(handle, SW_HIDE); AUnTrCrts(); if (#REPLACESTAGERRETRIES #) { int limit = #REPLACESTAGERRETRIESLIMIT #; int waitTime = #REPLACESTAGERRETRIESWAIT # *1000; var mre = new System.Threading.ManualResetEvent(false); while (true && limit > 0) { try { primer(); break; } catch { limit = limit - 1; mre.WaitOne(waitTime); waitTime = waitTime * 2; } } } else { primer(); } }
public GarbageCollection(int iInterval) { m_bContinueThread = true; m_GCWatchStopped = false; m_iInterval = iInterval; m_EventThreadEnded = new ManualResetEvent(false); }
/// <summary> /// Initializes the static data for the common communication channel properties. /// </summary> static ChannelStatus() { // Initialize the static fields. ChannelStatus.IsPrompted = false; ChannelStatus.tryToLoginEvent = new ManualResetEvent(false); ChannelStatus.logggedInEvent = new ManualResetEvent(false); ChannelStatus.secret = null; }
public static void Wait(this Task t) { var e = new System.Threading.ManualResetEvent(false); t.ContinueWith(_ => e.Set()); e.WaitOne(); }