Inheritance: EventWaitHandle
Example #1
2
 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;
 }
Example #2
1
		// 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 );
			}
		}
Example #3
1
 /// <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);
 }
        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);
        }
        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
        }
Example #6
1
        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");
        }
Example #8
1
		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]);
		}
Example #9
1
        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 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;
            }
        }
Example #13
1
        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);
        }
Example #14
1
        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
        }
Example #15
1
        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));
        }
Example #16
1
        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
        }
        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;
        }
Example #18
0
        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 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");
        }
 private void SetupData()
 {
     _closingRegister = new List<EventArgs>();
     _exceptionRegister = new List<ExceptionEventArgs>();
     _exceptionFired = new ManualResetEvent(false);
     _connectionTimeout = TimeSpan.FromSeconds(5);
 }
Example #21
0
 public ResultExecutionTask(IResult result, ActionExecutionContext context)
 {
     Result = result;
     Context = context;
     CompletionEventArgs = new ResultCompletionEventArgs();
     ExecutionCompleteWaitHandle = new ManualResetEvent(false);
 }
        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();
                });
        }
Example #23
0
        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();
                    });
                });
        }
Example #24
0
        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();
        }
Example #25
0
        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);
        }
        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 GarbageCollection(int iInterval)
 {
     m_bContinueThread = true;
     m_GCWatchStopped = false;
     m_iInterval = iInterval;
     m_EventThreadEnded = new ManualResetEvent(false);
 }
        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));
        }
        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 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));
        }