public void WaitOneNonAlertable_disposed_error() { var e = new ManualResetEvent(true); e.Dispose(); e.WaitOneNonAlertable(10); }
public void StartsElectionAfterElectionTimeout() { // arrange var resetEvent = new ManualResetEvent(false); var timeout = TimeSpan.FromMilliseconds(100); var configMock = new Mock<IServerConfiguration>(); configMock.Setup(mocked => mocked.ElectionTimeout).Returns(timeout); var config = configMock.Object; var scheduler = new EventLoop(); var serverMock = new Mock<IConsensusServerStateApi>(); serverMock.Setup(mocked => mocked.StartElection()).Callback(() => resetEvent.Set()); serverMock.Setup(mocked => mocked.Configuration).Returns(config); serverMock.Setup(mocked => mocked.Scheduler).Returns(scheduler); var server = serverMock.Object; var state = new Follower(server); // act state.Start(); var changedToCandidate = resetEvent.WaitOne(timeout + timeout); // assert Assert.That(changedToCandidate, Is.True, "An election timout should have occurred and the state should be changed to candidate"); // cleanup scheduler.Dispose(); resetEvent.Dispose(); }
public void Socket_ConnectAsyncDnsEndPoint_Success() { Assert.True(Capability.IPv4Support()); int port; SocketTestServer server = SocketTestServer.SocketTestServerFactory(IPAddress.Loopback, out port); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", port); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Assert.True(sock.ConnectAsync(args)); complete.WaitOne(); Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); complete.Dispose(); sock.Dispose(); server.Dispose(); }
public void Dispose() { if (reset != null) { abortWaiting = true; bpsLimit = Int32.MaxValue; reset.Dispose(); reset = null; } }
public DispatcherThread() { startedEvent = new ManualResetEvent(false); thread = new Thread(Run); thread.SetApartmentState(ApartmentState.STA); thread.Name = "DispatcherThread"; thread.Start(); startedEvent.WaitOne(); startedEvent.Dispose(); startedEvent = null; }
public void Socket_ConnectAsyncUnixDomainSocketEndPoint_Success() { string path = null; SocketTestServer server = null; UnixDomainSocketEndPoint endPoint = null; for (int attempt = 0; attempt < 5; attempt++) { path = GetRandomNonExistingFilePath(); endPoint = new UnixDomainSocketEndPoint(path); try { server = SocketTestServer.SocketTestServerFactory(endPoint, ProtocolType.Unspecified); break; } catch (SocketException) { // Path selection is contingent on a successful Bind(). // If it fails, the next iteration will try another path. } } try { Assert.NotNull(server); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = endPoint; args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); Assert.True(sock.ConnectAsync(args)); complete.WaitOne(); Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); complete.Dispose(); sock.Dispose(); server.Dispose(); } finally { File.Delete(path); } }
public void ProcessesCallbacks() { // arrange var worker = new EventLoopWorker(); var workDone = new ManualResetEvent(false); workDone.Reset(); // act worker.Schedule(() => workDone.Set()); // assert Assert.That(workDone.WaitOne(TimeSpan.FromMilliseconds(100)), Is.True, "Exepcted work to be done within 100ms"); // dispose stuff worker.Dispose(); workDone.Dispose(); }
public override bool Action(string action) { bool result = base.Action(action); if (result && action == ACTION_FILTER) { using (LogPurgerForm dlg = new LogPurgerForm()) { if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { using (Utils.FrameworkDataUpdater upd = new Utils.FrameworkDataUpdater(Core)) { _actionReady = new ManualResetEvent(false); Thread thrd = new Thread(new ThreadStart(this.purgeLogsWithFilterThreadMethod)); thrd.Start(); while (!_actionReady.WaitOne(10)) { System.Windows.Forms.Application.DoEvents(); } thrd.Join(); _actionReady.Dispose(); _actionReady = null; } } } } else if (result && action == ACTION_QUICKPURGE) { using (Utils.FrameworkDataUpdater upd = new Utils.FrameworkDataUpdater(Core)) { _actionReady = new ManualResetEvent(false); Thread thrd = new Thread(new ThreadStart(this.purgeLogsThreadMethod)); thrd.Start(); while (!_actionReady.WaitOne(10)) { System.Windows.Forms.Application.DoEvents(); } thrd.Join(); _actionReady.Dispose(); _actionReady = null; } } return result; }
public void SetIntervalCancel() { // arrange var loop = new EventLoop(); loop.Start(() => { }); var callbackinvoked = new ManualResetEvent(false); var callback = new Action(() => callbackinvoked.Set()); var timeout = TimeSpan.FromMilliseconds(100); // act var timer = loop.SetInterval(callback, timeout); timer.Cancel(); // assert Assert.That(callbackinvoked.WaitOne(timeout + timeout), Is.False); // cleanup loop.Dispose(); callbackinvoked.Dispose(); }
internal static TransportBase AcceptServerTransport(TransportSettings settings) { ManualResetEvent complete = new ManualResetEvent(false); int closed = 0; TransportBase transport = null; Action<TransportListener, TransportAsyncCallbackArgs> onTransport = (l, a) => { if (a.Exception != null) { Debug.WriteLine(a.Exception.Message); } else { Debug.WriteLine("Listener accepted a transport."); transport = a.Transport; } if (Interlocked.Exchange(ref closed, 1) == 0) { complete.Set(); } }; TransportListener listener = settings.CreateListener(); Debug.WriteLine("Listeners are waiting for connections..."); listener.Listen(onTransport); complete.WaitOne(); complete.Dispose(); transport.Closed += (s, a) => { listener.Close(); Debug.WriteLine("Listeners Closed."); }; return transport; }
/// <summary> /// Подождать пока объект не освободится /// </summary> /// <param name="actionKey">Уникальный ключ операции</param> public static void WaitWhileLocked(string actionKey) { var waitWhileNotUnlocked = new ManualResetEvent(true); lock (_lockerLock) { if (_lockedObjects.Contains(actionKey)) { if (!_waitingThreads.ContainsKey(actionKey)) { _waitingThreads.Add(actionKey, new List<ManualResetEvent>()); } _waitingThreads[actionKey].Add(waitWhileNotUnlocked); waitWhileNotUnlocked.Reset(); } else { waitWhileNotUnlocked.Set(); } } waitWhileNotUnlocked.WaitOne(); waitWhileNotUnlocked.Dispose(); }
public void FromCommandLineArgsRaceCondition() { // https://pytools.codeplex.com/workitem/1429 var mre = new ManualResetEvent(false); var tasks = new Task<bool>[100]; try { for (int i = 0; i < tasks.Length; i += 1) { tasks[i] = Task.Run(() => { mre.WaitOne(); using (var arg = VisualStudioProxy.FromProcessId(123)) { return arg is VisualStudioProxy; } }); } mre.Set(); Assert.IsTrue(Task.WaitAll(tasks, TimeSpan.FromSeconds(30.0))); Assert.IsTrue(tasks.All(t => t.Result)); } finally { mre.Dispose(); Task.WaitAll(tasks, TimeSpan.FromSeconds(30.0)); } }
public void Socket_ConnectAsyncDnsEndPoint_HostNotFound() { Assert.True(Capability.IPv4Support()); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("notahostname.invalid.corp.microsoft.com", UnusedPort); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { complete.WaitOne(); } AssertHostNotFoundOrNoData(args); complete.Dispose(); sock.Dispose(); }
/// <summary> /// /// </summary> /// <param name="usercontrol"></param> /// <returns>false if the user skipped.</returns> public Task<bool> AwaitUpdater(UserControl usercontrol, IProductUpdate productUpdate) { var updateSkeletonControl = usercontrol as Updating.Userinterface.UpdateSkeletonControl; if(updateSkeletonControl == null) throw new InvalidCastException("Control is not an UpdateSkeletonControl"); if(updateSkeletonControl.DataContext == null) throw new NullReferenceException("Datacontext of UpdateSkeletonControl not set"); var updatePropopsalViewModel = updateSkeletonControl.DataContext as UpdatePropopsalViewModel; if(updatePropopsalViewModel == null) throw new InvalidCastException("Datacontext of UpdateSkeletonControl is not of type UpdateProposalViewModel"); var manualResetEvent = new ManualResetEvent(false); updatePropopsalViewModel.ViewModelInteraction.CloseWindow = () => manualResetEvent.Set(); var awaiterTask = new Task<bool>(() => { // Wait for the async task to complete. manualResetEvent.WaitOne(); // Dispose the manual reset event. manualResetEvent.Dispose(); // Determine if we should close. return productUpdate.IsManadatory; }); awaiterTask.Start(); return awaiterTask; }
public async Task MiniBench() { const int M = 1 * 1000 * 1000; const int B = 100; const int ENTROPY = 10 * 1000; const int T = M / B; const int KEYSIZE = 10; const int VALUESIZE = 100; const bool RANDOM = false; var rnd = new Random(); //WARMUP using (var db = MemoryDatabase.CreateNew("FOO")) { await db.WriteAsync((tr) => tr.Set(db.Pack("hello"), Slice.FromString("world")), this.Cancellation); Slice.Random(rnd, KEYSIZE); Slice.Random(rnd, VALUESIZE); } Console.WriteLine("Inserting " + KEYSIZE + "-bytes " + (RANDOM ? "random" : "ordered") + " keys / " + VALUESIZE + "-bytes values, in " + T.ToString("N0") + " transactions"); bool random = RANDOM; string fmt = "D" + KEYSIZE; using (var db = MemoryDatabase.CreateNew("FOO")) { DumpMemory(collect: true); long total = 0; var payload = new byte[ENTROPY + VALUESIZE]; rnd.NextBytes(payload); // help with compression by doubling every byte for (int i = 0; i < payload.Length; i += 2) payload[i + 1] = payload[i]; var sw = Stopwatch.StartNew(); sw.Stop(); sw.Restart(); for (int i = 0; i < T; i++) { using (var tr = db.BeginTransaction(this.Cancellation)) { for (int j = 0; j < B; j++) { Slice key; if (random) { do { key = Slice.Random(rnd, KEYSIZE); } while (key[0] == 255); } else { int x = i * B + j; //x = x % 1000; key = Slice.FromString(x.ToString(fmt)); } tr.Set(key, Slice.Create(payload, rnd.Next(ENTROPY), VALUESIZE)); Interlocked.Increment(ref total); } await tr.CommitAsync().ConfigureAwait(false); } if (i % 1000 == 0) Console.Write(".");// + (i * B).ToString("D10")); } sw.Stop(); Console.WriteLine("done"); Console.WriteLine("* Inserted: " + total.ToString("N0") + " keys"); Console.WriteLine("* Elapsed : " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec"); Console.WriteLine("* TPS: " + (T / sw.Elapsed.TotalSeconds).ToString("N0") + " transaction/sec"); Console.WriteLine("* KPS: " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " key/sec"); Console.WriteLine("* BPS: " + ((total * (KEYSIZE + VALUESIZE)) / sw.Elapsed.TotalSeconds).ToString("N0") + " byte/sec"); DumpMemory(collect: true); db.Debug_Dump(false); DumpResult("WriteSeq" + B, total, total / B, sw.Elapsed); Console.WriteLine("Saving ..."); sw.Restart(); await db.SaveSnapshotAsync(".\\minibench.pndb"); sw.Stop(); Console.WriteLine("* Saved in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec"); Console.WriteLine("Warming up reads..."); var data = await db.GetValuesAsync(Enumerable.Range(0, 100).Select(i => Slice.FromString(i.ToString(fmt))), this.Cancellation); Console.WriteLine("Starting read tests..."); #region sequential reads //sw.Restart(); //for (int i = 0; i < total; i++) //{ // using (var tr = db.BeginReadOnlyTransaction()) // { // await tr.GetAsync(Slice.FromString(i.ToString(fmt))); // } //} //sw.Stop(); //Console.WriteLine("SeqRead1 : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps"); sw.Restart(); for (int i = 0; i < total; i += 10) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { await tr.GetValuesAsync(Enumerable.Range(i, 10).Select(x => Slice.FromString(x.ToString(fmt)))).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("SeqRead10 : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (10 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("SeqRead10", total, total / 10, sw.Elapsed); sw.Restart(); for (int i = 0; i < total; i += 10) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { await tr.GetValuesAsync(Enumerable.Range(i, 10).Select(x => Slice.FromString(x.ToString(fmt)))).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("SeqRead10S : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (10 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("SeqRead10S", total, total / 10, sw.Elapsed); sw.Restart(); for (int i = 0; i < total; i += 10) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { int x = i; int y = i + 10; await tr.GetRangeAsync( FdbKeySelector.FirstGreaterOrEqual(Slice.FromString(x.ToString(fmt))), FdbKeySelector.FirstGreaterOrEqual(Slice.FromString(y.ToString(fmt))) ).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("SeqRead10R : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (10 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("SeqRead10R", total, total / 10, sw.Elapsed); sw.Restart(); for (int i = 0; i < total; i += 100) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { await tr.GetValuesAsync(Enumerable.Range(i, 100).Select(x => Slice.FromString(x.ToString(fmt)))).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("SeqRead100 : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (100 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("SeqRead100", total, total / 100, sw.Elapsed); sw.Restart(); for (int i = 0; i < total; i += 100) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { await tr.Snapshot.GetValuesAsync(Enumerable.Range(i, 100).Select(x => Slice.FromString(x.ToString(fmt)))).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("SeqRead100S : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (100 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("SeqRead100S", total, total / 100, sw.Elapsed); sw.Restart(); for (int i = 0; i < total; i += 100) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { int x = i; int y = i + 100; await tr.GetRangeAsync( FdbKeySelector.FirstGreaterOrEqual(Slice.FromString(x.ToString(fmt))), FdbKeySelector.FirstGreaterOrEqual(Slice.FromString(y.ToString(fmt))) ).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("SeqRead100R : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (100 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("SeqRead100R", total, total / 100, sw.Elapsed); sw.Restart(); for (int i = 0; i < total; i += 100) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { int x = i; int y = i + 100; await tr.Snapshot.GetRangeAsync( FdbKeySelector.FirstGreaterOrEqual(Slice.FromString(x.ToString(fmt))), FdbKeySelector.FirstGreaterOrEqual(Slice.FromString(y.ToString(fmt))) ).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("SeqRead100RS: " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (100 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("SeqRead100RS", total, total / 100, sw.Elapsed); sw.Restart(); for (int i = 0; i < total; i += 1000) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { await tr.GetValuesAsync(Enumerable.Range(i, 1000).Select(x => Slice.FromString(x.ToString(fmt)))).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("SeqRead1k : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (1000 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("SeqRead1k", total, total / 1000, sw.Elapsed); #endregion DumpMemory(); #region random reads //sw.Restart(); //for (int i = 0; i < total; i++) //{ // using (var tr = db.BeginReadOnlyTransaction()) // { // int x = rnd.Next((int)total); // await tr.GetAsync(Slice.FromString(x.ToString(fmt))); // } //} //sw.Stop(); //Console.WriteLine("RndRead1 : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps"); sw.Restart(); for (int i = 0; i < total; i += 10) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { await tr.GetValuesAsync(Enumerable.Range(i, 10).Select(x => Slice.FromString(rnd.Next((int)total).ToString(fmt)))).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("RndRead10 : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (10 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("RndRead10", total, total / 10, sw.Elapsed); sw.Restart(); for (int i = 0; i < total; i += 10) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { await tr.Snapshot.GetValuesAsync(Enumerable.Range(i, 10).Select(x => Slice.FromString(rnd.Next((int)total).ToString(fmt)))).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("RndRead10S : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (10 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("RndRead10S", total, total / 10, sw.Elapsed); sw.Restart(); for (int i = 0; i < total; i += 10) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { int x = rnd.Next((int)total - 10); int y = x + 10; await tr.GetRangeAsync( FdbKeySelector.FirstGreaterOrEqual(Slice.FromString(x.ToString(fmt))), FdbKeySelector.FirstGreaterOrEqual(Slice.FromString(y.ToString(fmt))) ).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("RndRead10R : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (10 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("RndRead10R", total, total / 10, sw.Elapsed); sw.Restart(); for (int i = 0; i < total; i += 100) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { await tr.GetValuesAsync(Enumerable.Range(i, 100).Select(x => Slice.FromString(rnd.Next((int)total).ToString(fmt)))).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("RndRead100 : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (100 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("RndRead100", total, total / 100, sw.Elapsed); sw.Restart(); for (int i = 0; i < total; i += 1000) { using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { await tr.GetValuesAsync(Enumerable.Range(i, 1000).Select(x => Slice.FromString(rnd.Next((int)total).ToString(fmt)))).ConfigureAwait(false); } } sw.Stop(); //Console.WriteLine("RndRead1k : " + total.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (total / sw.Elapsed.TotalSeconds).ToString("N0") + " kps, " + (total / (1000 * sw.Elapsed.TotalSeconds)).ToString("N0") + " tps"); DumpResult("RndRead1k", total, total / 1000, sw.Elapsed); #endregion DumpMemory(); #region Parallel Reads... int CPUS = Environment.ProcessorCount; long read = 0; var mre = new ManualResetEvent(false); var tasks = Enumerable .Range(0, CPUS) .Select(k => Task.Run(async () => { var rndz = new Random(k); mre.WaitOne(); int keys = 0; for (int j = 0; j < 20; j++) { for (int i = 0; i < total / CPUS; i += 100) { int pp = i;// rndz.Next((int)total - 10); using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { var res = await tr.GetValuesAsync(Enumerable.Range(i, 100).Select(x => Slice.FromString((pp + x).ToString(fmt)))).ConfigureAwait(false); keys += res.Length; } } } Interlocked.Add(ref read, keys); return keys; })).ToArray(); sw.Restart(); mre.Set(); await Task.WhenAll(tasks); sw.Stop(); mre.Dispose(); //Console.WriteLine("ParaSeqRead: " + read.ToString("N0") + " keys in " + sw.Elapsed.TotalSeconds.ToString("N3") + " sec => " + (read / sw.Elapsed.TotalSeconds).ToString("N0") + " kps"); DumpResult("ParaSeqRead", read, read / 100, sw.Elapsed); read = 0; mre = new ManualResetEvent(false); tasks = Enumerable .Range(0, CPUS) .Select(k => Task.Run(async () => { var rndz = new Random(k); mre.WaitOne(); int keys = 0; for (int j = 0; j < 20; j++) { for (int i = 0; i < total / CPUS; i += 100) { int pp = i;// rndz.Next((int)total - 100); using (var tr = db.BeginReadOnlyTransaction(this.Cancellation)) { var res = await tr.GetRangeAsync( FdbKeySelector.FirstGreaterOrEqual(Slice.FromString(pp.ToString(fmt))), FdbKeySelector.FirstGreaterOrEqual(Slice.FromString((pp + 100).ToString(fmt))) ).ConfigureAwait(false); keys += res.Count; } } } Interlocked.Add(ref read, keys); return keys; })).ToArray(); sw.Restart(); mre.Set(); await Task.WhenAll(tasks); sw.Stop(); mre.Dispose(); DumpResult("ParaSeqRange", read, read / 100, sw.Elapsed); #endregion DumpMemory(); } }
/// <summary> /// Stops the keep-alive timer, and waits until all timer callbacks have been /// executed. /// </summary> private void StopKeepAliveTimer() { if (_keepAliveTimer == null) return; var timerDisposed = new ManualResetEvent(false); _keepAliveTimer.Dispose(timerDisposed); timerDisposed.WaitOne(); timerDisposed.Dispose(); _keepAliveTimer = null; }
public void Socket_ConnectAsyncDnsEndPoint_Success(SocketImplementationType type) { Assert.True(Capability.IPv4Support()); int port; SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", port); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); complete.Dispose(); sock.Dispose(); server.Dispose(); }
static void testThreadLambda() { int nCount = 0; ThreadStart action = () => { WriteX(); lock(_locker) nCount++; }; new Thread(action).Start(); new Thread(action).Start(); new Thread(action).Start(); new Thread(action).Start(); new Thread(action).Start(); var signal = new ManualResetEvent(false); new Thread(() => { Console.WriteLine("Here is a thread who is Waiting for signal from somewhere..."); signal.WaitOne(); signal.Dispose(); Console.WriteLine("Got signal!"); }).Start(); WriteM(); // Task is in System.Threading.Tasks Task.Run(() => Console.WriteLine("T1: Hello from the thread pool")); Task.Run(() => Console.WriteLine("T2: Hello from the thread pool")); Task.Run(() => Console.WriteLine("T3: Hello from the thread pool")); Task.Run(() => Console.WriteLine("T4: Hello from the thread pool")); Task.Run(() => Console.WriteLine("T5: Hello from the thread pool")); Task.Run(() => Console.WriteLine("T6: Hello from the thread pool")); Task.Run(() => Console.WriteLine("TA: Hello from the thread pool")); Task.Run(() => Console.WriteLine("TB: Hello from the thread pool")); Task.Run(() => Console.WriteLine("TC: Hello from the thread pool")); Task.Run(() => Console.WriteLine("TD: Hello from the thread pool")); Task.Run(() => Console.WriteLine("TE: Hello from the thread pool")); Task.Run(() => Console.WriteLine("TF: Hello from the thread pool")); Task.Run(() => Console.WriteLine("t1: Hello from the thread pool")); Task.Run(() => Console.WriteLine("t2: Hello from the thread pool")); Task.Run(() => Console.WriteLine("t3: Hello from the thread pool")); Task.Run(() => Console.WriteLine("t4: Hello from the thread pool")); Task.Run(() => Console.WriteLine("t5: Hello from the thread pool")); Task.Run(() => Console.WriteLine("t6: Hello from the thread pool")); Task.Run(() => Console.WriteLine("tA: Hello from the thread pool")); Task.Run(() => Console.WriteLine("tB: Hello from the thread pool")); Task.Run(() => Console.WriteLine("tC: Hello from the thread pool")); Task.Run(() => Console.WriteLine("tD: Hello from the thread pool")); Task.Run(() => Console.WriteLine("tE: Hello from the thread pool")); Task.Run(() => Console.WriteLine("tF: Hello from the thread pool")); Console.WriteLine("Main thread fire the signal"); signal.Set(); Thread.Sleep(500); Console.WriteLine("exit when nCount is {0}", nCount); }
/// <summary> /// This method lazily initializes the event object. It uses CAS to guarantee that /// many threads racing to call this at once don't result in more than one event /// being stored and used. The event will be signaled or unsignaled depending on /// the state of the thin-event itself, with synchronization taken into account. /// </summary> /// <returns>True if a new event was created and stored, false otherwise.</returns> private bool LazyInitializeEvent() { bool preInitializeIsSet = IsSet; ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet); // We have to CAS this in case we are racing with another thread. We must // guarantee only one event is actually stored in this field. if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null) { // We raced with someone else and lost. Destroy the garbage event. newEventObj.Dispose(); return false; } else { // Now that the event is published, verify that the state hasn't changed since // we snapped the preInitializeState. Another thread could have done that // between our initial observation above and here. The barrier incurred from // the CAS above (in addition to m_state being volatile) prevents this read // from moving earlier and being collapsed with our original one. bool currentIsSet = IsSet; if (currentIsSet != preInitializeIsSet) { Contract.Assert(currentIsSet, "The only safe concurrent transition is from unset->set: detected set->unset."); // We saw it as unsignaled, but it has since become set. lock (newEventObj) { // If our event hasn't already been disposed of, we must set it. if (m_eventObj == newEventObj) { newEventObj.Set(); } } } return true; } }
/// <summary> /// Allows to stop the adapter. /// /// Before returning, and if it is so configured, /// the adapter sends a "suspend" request to /// all the currently registred fixtures. /// </summary> public void Stop() { _logger.InfoFormat("Adapter is stopping"); try { if (_trigger != null) { var wait_handler = new ManualResetEvent(false); _trigger.Dispose(wait_handler); wait_handler.WaitOne(); wait_handler.Dispose(); _trigger = null; _fixtureManager.Dispose(); } if (PlatformConnector != null) PlatformConnector.Dispose(); UDAPIService.Disconnect(); } catch (Exception e) { _logger.Error("An error occured while disposing the adapter", e); } _stats.SetValue(AdapterCoreKeys.ADAPTER_STARTED, "0"); _logger.InfoFormat("Adapter stopped"); }
public static void Dispose() { var wh = new ManualResetEvent(false); wh.Dispose(); Assert.Throws<ObjectDisposedException>(() => wh.WaitOne(0)); }
public void CloneResult_ThrowsOnRunningTask() { var wh = new ManualResetEvent(false); var taskStartedWH = new ManualResetEvent(false); var task = Task.Factory.StartNew(() => { taskStartedWH.Set(); wh.WaitOne(); wh.Dispose(); return ""; }); taskStartedWH.WaitOne(); taskStartedWH.Dispose(); Debug.Assert(task.Status == TaskStatus.Running, "task.Status == TaskStatus.Running"); try { task.CloneResult(); } finally { wh.Set(); } }
public void Socket_StaticConnectAsync_HostNotFound() { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("notahostname.invalid.corp.microsoft.com", UnusedPort); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; bool willRaiseEvent = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args); if (!willRaiseEvent) { OnConnectAsyncCompleted(null, args); } Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); AssertHostNotFoundOrNoData(args); Assert.Null(args.ConnectSocket); complete.Dispose(); }
public void Socket_ConnectAsyncDnsEndPoint_ConnectionRefused() { Assert.True(Capability.IPv4Support()); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); } Assert.Equal(SocketError.ConnectionRefused, args.SocketError); Assert.True(args.ConnectByNameError is SocketException); Assert.Equal(SocketError.ConnectionRefused, ((SocketException)args.ConnectByNameError).SocketErrorCode); complete.Dispose(); sock.Dispose(); }
// Returns true if this call created the event. // May return with a null handle. That means it thought it got one, but it was disposed in the mean time. private bool LazilyCreateEvent(out ManualResetEvent waitHandle) { waitHandle = new ManualResetEvent(false); try { if (Interlocked.CompareExchange(ref _event, waitHandle, null) == null) { if (InternalPeekCompleted) { waitHandle.Set(); } return true; } else { waitHandle.Dispose(); waitHandle = (ManualResetEvent)_event; // There's a chance here that _event became null. But the only way is if another thread completed // in InternalWaitForCompletion and disposed it. If we're in InternalWaitForCompletion, we now know // IsCompleted is set, so we can avoid the wait when waitHandle comes back null. AsyncWaitHandle // will try again in this case. return false; } } catch { // This should be very rare, but doing this will reduce the chance of deadlock. _event = null; if (waitHandle != null) { waitHandle.Dispose(); } throw; } }
public override bool Action(string action) { bool result = base.Action(action); if (result && action == ACTION_CLEARFLAGS_SELECTED) { List<Framework.Data.Geocache> gcList = Utils.DataAccess.GetSelectedGeocaches(Core.Geocaches); if (gcList == null || gcList.Count == 0) { System.Windows.Forms.MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation(STR_NOCACHES_SELECTED), Utils.LanguageSupport.Instance.GetTranslation(STR_INFORMATION), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } else { using (Utils.FrameworkDataUpdater upd = new Utils.FrameworkDataUpdater(Core)) { foreach (Framework.Data.Geocache gc in gcList) { gc.Flagged = false; } } } } else if (result && action == ACTION_CLEARFLAGS_ALL) { using (Utils.FrameworkDataUpdater upd = new Utils.FrameworkDataUpdater(Core)) { foreach (Framework.Data.Geocache gc in Core.Geocaches) { gc.Flagged = false; } } } else if (result && action == ACTION_SELECTION) { List<Framework.Data.Geocache> gcList = Utils.DataAccess.GetSelectedGeocaches(Core.Geocaches); if (gcList == null || gcList.Count == 0) { System.Windows.Forms.MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation(STR_NOCACHES_SELECTED), Utils.LanguageSupport.Instance.GetTranslation(STR_INFORMATION), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } else { string msg = string.Format("{0} {1} {2}", Utils.LanguageSupport.Instance.GetTranslation(STR_ABOUTTODELETE), gcList.Count, Utils.LanguageSupport.Instance.GetTranslation(STR_GEOCACHES)); if (System.Windows.Forms.MessageBox.Show(msg, Utils.LanguageSupport.Instance.GetTranslation(STR_WARNING), System.Windows.Forms.MessageBoxButtons.OKCancel, System.Windows.Forms.MessageBoxIcon.Warning, System.Windows.Forms.MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.OK) { using (Utils.FrameworkDataUpdater upd = new Utils.FrameworkDataUpdater(Core)) { if (Core.ActiveGeocache != null && gcList.Contains(Core.ActiveGeocache)) { Core.ActiveGeocache = null; } _gcList = gcList; _actionReady = new ManualResetEvent(false); Thread thrd = new Thread(new ThreadStart(this.deleteSelectionThreadMethod)); thrd.Start(); while (!_actionReady.WaitOne(10)) { System.Windows.Forms.Application.DoEvents(); } thrd.Join(); _actionReady.Dispose(); _actionReady = null; } } } } else if (result && action == ACTION_ACTIVE) { if (Core.ActiveGeocache == null) { System.Windows.Forms.MessageBox.Show(Utils.LanguageSupport.Instance.GetTranslation(STR_NOCACHES_SELECTED), Utils.LanguageSupport.Instance.GetTranslation(STR_INFORMATION), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } else { string msg = string.Format("{0} {1} {2}", Utils.LanguageSupport.Instance.GetTranslation(STR_ABOUTTODELETE), 1, Utils.LanguageSupport.Instance.GetTranslation(STR_GEOCACHES)); if (System.Windows.Forms.MessageBox.Show(msg, Utils.LanguageSupport.Instance.GetTranslation(STR_WARNING), System.Windows.Forms.MessageBoxButtons.OKCancel, System.Windows.Forms.MessageBoxIcon.Warning, System.Windows.Forms.MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.OK) { using (Utils.FrameworkDataUpdater upd = new Utils.FrameworkDataUpdater(Core)) { Utils.DataAccess.DeleteGeocache(Core, Core.ActiveGeocache); Core.ActiveGeocache = null; } } } } return result; }
private void ApplyReceiveWorkaround() { _logger.Trace("Applying receive workaround for WP7"); var waitEvent = new ManualResetEvent(false); var tempEventArgs = new SocketAsyncEventArgs(); tempEventArgs.SetBuffer(new byte[] { 0xff }, 0, 1); tempEventArgs.RemoteEndPoint = _socketOperation.RemoteEndPoint; tempEventArgs.Completed += (s, e) => waitEvent.Set(); _currentSocket.SendToAsync(tempEventArgs); waitEvent.WaitOne(); waitEvent.Dispose(); tempEventArgs.Dispose(); _receiveWorkaroundApplied = true; }
public static void Close(this ManualResetEvent ev) { ev.Dispose(); }
public void Socket_StaticConnectAsync_ConnectionRefused() { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; bool willRaiseEvent = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args); if (!willRaiseEvent) { OnConnectAsyncCompleted(null, args); } Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); Assert.Equal(SocketError.ConnectionRefused, args.SocketError); Assert.True(args.ConnectByNameError is SocketException); Assert.Equal(SocketError.ConnectionRefused, ((SocketException)args.ConnectByNameError).SocketErrorCode); Assert.Null(args.ConnectSocket); complete.Dispose(); }
public FolderMonitor(string path, string pattern, Action<string[]> callback) { if (callback == null || string.IsNullOrWhiteSpace(path)) { return; } if (string.IsNullOrWhiteSpace(pattern)) { pattern = "*.*"; } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } mre = new ManualResetEvent(false); watcher = new FileSystemWatcher(path); watcher.Changed += Watcher_Changed; watcher.EnableRaisingEvents = true; Thread th = new Thread(new ThreadStart(() => { try { mre.WaitOne(); while (!isexit) { Thread.Sleep(500); var files = Directory.GetFiles(path, pattern, SearchOption.AllDirectories); if (files.Length > 0) { callback(files); } mre.WaitOne(); } } catch (Exception ex) { log.e(ex); } finally { mre.Dispose(); watcher.Dispose(); isdisposed = true; } })); th.Start(); }
public void CloneResult_ThrowsOnWaitingForChildrenToCompleteTask() { var wh = new ManualResetEvent(false); var taskStartedWH = new ManualResetEvent(false); var childWH = new ManualResetEvent(false); var childTaskStartedWH = new ManualResetEvent(false); var task = Task.Factory.StartNew(() => { taskStartedWH.Set(); wh.WaitOne(); wh.Dispose(); return ""; }); var childTask = task.ContinueWith(x => { childTaskStartedWH.Set(); childWH.WaitOne(); childWH.Dispose(); return x; }, TaskContinuationOptions.AttachedToParent); taskStartedWH.WaitOne(); taskStartedWH.Dispose(); wh.Set(); childTaskStartedWH.WaitOne(); childTaskStartedWH.Dispose(); Debug.Assert(task.Status == TaskStatus.WaitingForChildrenToComplete, "task.Status == TaskStatus.WaitingForChildrenToComplete"); try { task.CloneResult(); } finally { childWH.Set(); } }
public void LoadGCVoteData(Utils.BasePlugin.Plugin p) { _activePlugin = p; _actionDone = new ManualResetEvent(false); _core.Geocaches.BeginUpdate(); Thread thrd = new Thread(new ThreadStart(this.LoadGCVoteDataThreadMethod)); thrd.Start(); while (!_actionDone.WaitOne(100)) { System.Windows.Forms.Application.DoEvents(); } thrd.Join(); _actionDone.Dispose(); _actionDone = null; _core.Geocaches.EndUpdate(); }