public void TestOceOnTerminatedLifetime() { var n = 100_000_000L; long expected = n * (n - 1) / 2; bool flag = false; var lazy = new ProactiveLazy <long>(Lifetime.Eternal, () => { SpinWaitEx.SpinUntil(() => flag); return(42); }); try { //canceled before wait started Assert.That(() => lazy.GetOrWait(Lifetime.Terminated), Throws.InstanceOf <OperationCanceledException>()); //canceled after wait started var ld = new LifetimeDefinition(); ThreadPool.QueueUserWorkItem(_ => { Thread.Sleep(100); ld.Terminate(); }); Assert.That(() => lazy.GetOrWait(Lifetime.Terminated), Throws.InstanceOf <OperationCanceledException>()); } finally { flag = true; } }
public void TestPause() { int x = 0; var buffer = new ByteBufferAsyncProcessor("TestAsyncProcessor", 1, delegate(byte[] data, int offset, int len, ref long seqN) { x += data[offset]; }); var reason1 = "reason1"; var reason2 = "reason2"; Assert.True(buffer.Pause(reason1)); Assert.False(buffer.Pause(reason1)); Assert.True(buffer.Pause(reason2)); Assert.False(buffer.Pause(reason2)); buffer.Start(); buffer.Put(new byte[] { 1, 2, 3 }); Thread.Sleep(50); Assert.AreEqual(0, x); Assert.True(buffer.Resume(reason1)); Assert.False(buffer.Resume(reason1)); Thread.Sleep(50); Assert.AreEqual(0, x); Assert.True(buffer.Resume(reason2)); Assert.False(buffer.Resume(reason2)); Assert.False(buffer.Resume(reason2)); SpinWaitEx.SpinUntil(() => buffer.AllDataProcessed); Assert.AreEqual(6, x); }
// only for test purposes public Task Delay(int ms, CancellationToken token) { return(Task.Factory.StartNew(() => { SpinWaitEx.SpinUntil(Lifetime.Eternal, TimeSpan.FromMilliseconds(ms), () => token.IsCancellationRequested); token.ThrowIfCancellationRequested(); }, token)); }
private void After() { Logging.LogWithTime("Spinning started"); SpinWaitEx.SpinUntil(ModelLifetime, SpinningTimeout, () => false); Logging.LogWithTime("Spinning finished"); SocketLifetimeDef.Terminate(); ModelLifetimeDef.Terminate(); }
protected void After() { SpinWaitEx.SpinUntil(ModelLifetime, 10_000, () => Finished); SpinWaitEx.SpinUntil(ModelLifetime, 1_000, () => false); SocketLifetimeDef.Terminate(); ModelLifetimeDef.Terminate(); using (myOutputFile) { myOutputFile.Write(Printer.ToString()); } }
public async Task TestAsyncExternalCancellation() { bool?isCancelled = null; await TestAsyncCalls(model => { model.AlwaysCancelled(). ContinueWith(t => isCancelled = t.IsCanceled, TaskContinuationOptions.ExecuteSynchronously); }); SpinWaitEx.SpinUntil(TimeSpan.FromSeconds(1), () => isCancelled != null); Assert.AreEqual(true, isCancelled); }
protected override IScheduler CreateScheduler(bool isServer) { string name = (isServer ? "server" : "client") + " scheduler"; IScheduler result = null; var thread = new Thread(() => SingleThreadScheduler.RunInCurrentStackframe(TestLifetime, name, s => result = s)) { Name = name }; thread.Start(); SpinWaitEx.SpinUntil(() => result != null); return(result); }
public void TestAsync() { string result = null; TestAsyncCalls(model => { model.GetStringAsync().ContinueWith(t => result = t.Result, TaskContinuationOptions.ExecuteSynchronously); }); #if NET35 // it seems like ExecuteSynchronously does not work in NET35 SpinWaitEx.SpinUntil(TimeSpan.FromSeconds(1), () => result != null); #endif Assert.AreEqual(result, "result"); }
public async Task TestAsync() { string result = null; await TestAsyncCalls(async model => { result = await model.GetStringAsync(); }); #if NET35 // it seems like ExecuteSynchronously does not work in NET35 SpinWaitEx.SpinUntil(TimeSpan.FromSeconds(1), () => result != null); #endif Assert.AreEqual(result, "result"); }
public async Task TestAsync() { bool?isCancelled = null; var testAsyncCalls = TestAsyncCalls(model => { var cancellationLifetimeDef = new LifetimeDefinition(); model.GetInt(100, cancellationLifetimeDef.Lifetime). ContinueWith(t => isCancelled = t.IsCanceled, TaskContinuationOptions.ExecuteSynchronously); }); SpinWaitEx.SpinUntil(TimeSpan.FromSeconds(1), () => isCancelled != null); await testAsyncCalls; Assert.AreEqual(false, isCancelled); }
public async Task TestAsyncCancel() { bool?isCancelled = null; await TestAsyncCalls(model => { var cancellationLifetimeDef = new LifetimeDefinition(); model.GetLongRunningInt(100, cancellationLifetimeDef.Lifetime). ContinueWith(t => isCancelled = t.IsCanceled, TaskContinuationOptions.ExecuteSynchronously); Task.Run(async() => { await Task.Delay(10); cancellationLifetimeDef.Terminate(); }); cancellationLifetimeDef.Terminate(); }); SpinWaitEx.SpinUntil(TimeSpan.FromSeconds(1), () => isCancelled != null); Assert.AreEqual(true, isCancelled); }
private void TestDisconnectBase(Action <List <int>, int> advise) { var timeout = TimeSpan.FromSeconds(1); Lifetime.Using(lifetime => { SynchronousScheduler.Instance.SetActive(lifetime); var serverProtocol = Server(lifetime, null); var clientProtocol = Client(lifetime, serverProtocol); var sp = new RdSignal <int>().Static(1); sp.Bind(lifetime, serverProtocol, Top); var cp = new RdSignal <int>().Static(1); cp.Bind(lifetime, clientProtocol, Top); var log = new List <int>(); sp.Advise(lifetime, i => advise(log, i)); cp.Fire(1); cp.Fire(2); Assert.True(SpinWaitEx.SpinUntil(timeout, () => log.Count == 2)); Assert.AreEqual(new List <int> { 1, 2 }, log); CloseSocket(clientProtocol); cp.Fire(3); cp.Fire(4); Assert.True(SpinWaitEx.SpinUntil(timeout, () => log.Count == 4)); Assert.AreEqual(new List <int> { 1, 2, 3, 4 }, log); CloseSocket(serverProtocol); cp.Fire(5); cp.Fire(6); Assert.True(SpinWaitEx.SpinUntil(timeout, () => log.Count == 6)); Assert.AreEqual(new List <int> { 1, 2, 3, 4, 5, 6 }, log); }); }
public void TestOverriddenHandlerScheduler() { ClientWire.AutoTransmitMode = true; ServerWire.AutoTransmitMode = true; var scheduler = SingleThreadScheduler.RunOnSeparateThread(TestLifetime, "Background scheduler"); var callsite = BindToServer(LifetimeDefinition.Lifetime, new RdCall <int, string>(), ourKey); var endpoint = BindToClient(LifetimeDefinition.Lifetime, new RdCall <int, string>(), ourKey); Assert.IsFalse(scheduler.IsActive); var point1 = false; var point2 = false; var thread = Thread.CurrentThread; endpoint.Set(i => { Assert.IsTrue(scheduler.IsActive); Assert.AreNotEqual(thread, Thread.CurrentThread); Volatile.Write(ref point1, true); SpinWaitEx.SpinUntil(TestLifetime, TimeSpan.FromSeconds(10), () => point2); Assert.IsTrue(point2); return(i.ToString()); }, handlerScheduler: scheduler); Assert.IsFalse(scheduler.IsActive); var task = callsite.Start(0); var result = task.Result; Assert.IsFalse(result.Maybe.HasValue); SpinWaitEx.SpinUntil(TestLifetime, TimeSpan.FromSeconds(10), () => point1); Assert.IsTrue(point1); Assert.IsFalse(result.Maybe.HasValue); Volatile.Write(ref point2, true); SpinWaitEx.SpinUntil(TestLifetime, () => result.Maybe.HasValue); Assert.AreEqual("0", result.Value.Result); }
public void TestBindable() { ClientWire.AutoTransmitMode = true; ServerWire.AutoTransmitMode = true; var call1 = new RdCall <Unit, RdSignal <int> >(Serializers.ReadVoid, Serializers.WriteVoid, RdSignal <int> .Read, RdSignal <int> .Write); var call2 = new RdCall <Unit, RdSignal <int> >(Serializers.ReadVoid, Serializers.WriteVoid, RdSignal <int> .Read, RdSignal <int> .Write); var respSignal = new RdSignal <int>(); var endpointLfTerminated = false; call2.Set((endpointLf, _) => { endpointLf.OnTermination(() => endpointLfTerminated = true); return(RdTask <RdSignal <int> > .Successful(respSignal)); }); var serverEntity = BindToServer(LifetimeDefinition.Lifetime, call1, ourKey); var clientEntity = BindToClient(LifetimeDefinition.Lifetime, call2, ourKey); var ld = new LifetimeDefinition(); var lf = ld.Lifetime; var signal = call1.Start(lf, Unit.Instance).AsTask().GetOrWait(lf); var log = new List <int>(); signal.Advise(Lifetime.Eternal, v => { log.Add(v); Console.WriteLine(v); }); respSignal.Fire(1); respSignal.Fire(2); respSignal.Fire(3); ld.Terminate(); Assert.False(respSignal.IsBound); SpinWaitEx.SpinUntil(() => log.Count >= 3); Thread.Sleep(100); Assert.AreEqual(new [] { 1, 2, 3 }, log.ToArray()); Assert.True(endpointLfTerminated); }
public void TestOneProducer() { var processed = 0; var buffer = new ByteBufferAsyncProcessor("TestAsyncProcessor", 10, delegate(byte[] data, int offset, int len, ref long seqN) { Assert.Greater(len, 0); for (int i = 0; i < len - 1; i++) { Assert.AreEqual(data[offset + i + 1], (byte)(data[offset + i] + 1)); } processed += len; }); byte b = 0; int l = 0; var toProcess = 0; for (int i = 0; i < 300; i++) { toProcess += l; byte[] p = new byte[l++]; for (int j = 0; j < p.Length; j++) { p[j] = b++; } buffer.Put(p); if (i == 20) { buffer.Start(); //testing delayed start } if (i > 0 && i % 50 == 0) { SpinWaitEx.SpinUntil(() => buffer.AllDataProcessed); //give it to process } } SpinWaitEx.SpinUntil(() => buffer.AllDataProcessed); //give it to process Assert.AreEqual(toProcess, processed); Assert.True(buffer.Stop(1000)); }
public void TestDisconnect() { Lifetime.Using(lifetime => { SynchronousScheduler.Instance.SetActive(lifetime); var serverProtocol = Server(lifetime, null); var clientProtocol = Client(lifetime, serverProtocol); var sp = new RdSignal <int>().Static(1); sp.Bind(lifetime, serverProtocol, Top); var cp = new RdSignal <int>().Static(1); cp.Bind(lifetime, clientProtocol, Top); var log = new List <int>(); sp.Advise(lifetime, i => log.Add(i)); cp.Fire(1); cp.Fire(2); SpinWaitEx.SpinUntil(() => log.Count == 2); Assert.AreEqual(new List <int> { 1, 2 }, log); CloseSocket(clientProtocol); cp.Fire(3); cp.Fire(4); SpinWaitEx.SpinUntil(() => log.Count == 4); Assert.AreEqual(new List <int> { 1, 2, 3, 4 }, log); CloseSocket(serverProtocol); cp.Fire(5); cp.Fire(6); SpinWaitEx.SpinUntil(() => log.Count == 6); Assert.AreEqual(new List <int> { 1, 2, 3, 4, 5, 6 }, log); }); }
public bool PumpAndWaitFor(Lifetime lifetime, TimeSpan timeout, Func <bool> condition) { var shouldPump = IsActive; return(SpinWaitEx.SpinUntil(lifetime, timeout, () => { if (condition()) { return true; } if (shouldPump) { ExecuteOneAction(blockIfNoActionAvailable: false); } return false; })); }
public void TestClean() { int x = 0; var buffer = new ByteBufferAsyncProcessor("TestAsyncProcessor", 1, delegate(byte[] data, int offset, int len, ref long seqN) { x += data[offset]; }); buffer.Put(new byte[] { 1 }); buffer.Put(new byte[] { 2 }); buffer.Put(new byte[] { 3 }); Assert.False(buffer.AllDataProcessed); //not started buffer.Clear(); Assert.True(buffer.AllDataProcessed); buffer.Start(); buffer.Put(new byte[] { 1, 2, 3 }); SpinWaitEx.SpinUntil(() => buffer.AllDataProcessed); Assert.AreEqual(6, x); }
public void TestTerminationWithAsyncTimeout() { var lin = new Linearization(); lin.Enable(); var log = new List <int>(); var task = Task.Run(() => { var first = lt.TryExecute(() => { log.Add(0); Assert.AreEqual(LifetimeStatus.Alive, lt.Status); Assert.True(lt.IsAlive); lin.Point(0); log.Add(1); SpinWaitEx.SpinUntil(() => def.Status == LifetimeStatus.Canceling); Assert.False(lt.IsAlive); }); //shouldn't execute var second = lt.TryExecute(() => { log.Add(2); }); Assert.True(first.Succeed); Assert.False(second.Succeed); }); def.Lifetime.OnTermination(() => { log.Add(-1); }); lin.Point(1); def.Terminate(); lin.Point(2); task.Wait(); Assert.AreEqual(new [] { 0, 1, -1 }, log.ToArray()); }
public void TestSocketFactory() { var sLifetime = new LifetimeDefinition(); var factory = new SocketWire.ServerFactory(sLifetime.Lifetime, SynchronousScheduler.Instance); var lf1 = new LifetimeDefinition(); new SocketWire.Client(lf1.Lifetime, SynchronousScheduler.Instance, factory.LocalPort); SpinWaitEx.SpinUntil(() => factory.Connected.Count == 1); var lf2 = new LifetimeDefinition(); new SocketWire.Client(lf2.Lifetime, SynchronousScheduler.Instance, factory.LocalPort); SpinWaitEx.SpinUntil(() => factory.Connected.Count == 2); lf1.Terminate(); SpinWaitEx.SpinUntil(() => factory.Connected.Count == 1); sLifetime.Terminate(); SpinWaitEx.SpinUntil(() => factory.Connected.Count == 0); }
public void TestCancellation() { ClientWire.AutoTransmitMode = true; ServerWire.AutoTransmitMode = true; var serverEntity = BindToServer(LifetimeDefinition.Lifetime, new RdCall <Unit, string>(), ourKey); var clientEntity = BindToClient(LifetimeDefinition.Lifetime, CreateEndpoint <Unit, string>(x => x.ToString()), ourKey); bool handlerFinished = false; bool handlerCompletedSuccessfully = false; clientEntity.Set(async(lf, req) => { try { await Task.Delay(500, lf); handlerCompletedSuccessfully = true; } finally { handlerFinished = true; } return(""); }); //1. explicit cancellation var ld = new LifetimeDefinition(); var task = serverEntity.Start(ld.Lifetime, Unit.Instance).AsTask(); ld.Terminate(); SpinWaitEx.SpinUntil(() => task.IsCompleted); Assert.True(task.IsOperationCanceled()); SpinWaitEx.SpinUntil(() => handlerFinished); Assert.False(handlerCompletedSuccessfully); //2. no cancellation handlerFinished = false; handlerCompletedSuccessfully = false; task = serverEntity.Start(new LifetimeDefinition().Lifetime, Unit.Instance).AsTask(); SpinWaitEx.SpinUntil(() => task.IsCompleted); Assert.False(task.IsOperationCanceled()); SpinWaitEx.SpinUntil(() => handlerFinished); Assert.True(handlerCompletedSuccessfully); //3. cancellation from parent lifetime handlerFinished = false; handlerCompletedSuccessfully = false; task = serverEntity.Start(new LifetimeDefinition().Lifetime, Unit.Instance).AsTask(); LifetimeDefinition.Terminate(); SpinWaitEx.SpinUntil(() => task.IsCompleted); Assert.True(task.IsOperationCanceled()); SpinWaitEx.SpinUntil(() => handlerFinished); Assert.False(handlerCompletedSuccessfully); }
public static bool Wait <T>(this IRdTask <T> task, TimeSpan timeout) => SpinWaitEx.SpinUntil(Lifetime.Eternal, timeout, () => task.Result.HasValue());
public unsafe void TestReprocess() { long prev = 0; ByteBufferAsyncProcessor buffer = null; List <long> log = new List <long>(); buffer = new ByteBufferAsyncProcessor("TestAsyncProcessor", 8, delegate(byte[] data, int offset, int len, ref long seqN) { try { fixed(byte *b = data) { long l = UnsafeReader.CreateReader(b, 8).ReadLong(); if (seqN != 0) { Assert.AreEqual(l, seqN); } seqN = l; log.Add(l); Assert.True(l > prev); prev = l; } } catch (Exception e) { Log.Root.Error(e); } }); buffer.ShrinkIntervalMs = 10; buffer.Start(); PutLong(buffer, 1); PutLong(buffer, 2); PutLong(buffer, 3); PutLong(buffer, 4); SpinWaitEx.SpinUntil(() => buffer.AllDataProcessed); Assert.AreEqual(new List <int> { 1, 2, 3, 4 }, log); buffer.Acknowledge(2); prev = 2; buffer.ReprocessUnacknowledged(); PutLong(buffer, 5); SpinWaitEx.SpinUntil(() => buffer.AllDataProcessed); Assert.AreEqual(new List <int> { 1, 2, 3, 4, 3, 4, 5 }, log); buffer.Acknowledge(5); buffer.ReprocessUnacknowledged(); SpinWaitEx.SpinUntil(() => buffer.AllDataProcessed); Assert.AreEqual(new List <int> { 1, 2, 3, 4, 3, 4, 5 }, log); }
private void WaitMessages() { bool IsIdle(IRdDynamic p) => ((SingleThreadScheduler)p.Proto.Scheduler).IsIdle; SpinWaitEx.SpinUntil(() => IsIdle(ServerProtocol) && IsIdle(ClientProtocol)); }
public void TestSimple() { // using var factory = Log.UsingLogFactory(new TextWriterLogFactory(Console.Out, LoggingLevel.TRACE)); Lifetime.Using(lifetime => { var proxyLifetimeDefinition = lifetime.CreateNested(); var proxyLifetime = proxyLifetimeDefinition.Lifetime; { SynchronousScheduler.Instance.SetActive(lifetime); var serverProtocol = SocketWireTest.Server(lifetime); var proxy = new SocketProxy("TestProxy", proxyLifetime, serverProtocol).With(socketProxy => socketProxy.Start()); Thread.Sleep(SocketWireTest.DefaultTimeout); var clientProtocol = SocketWireTest.Client(lifetime, proxy.Port); var sp = new RdSignal <int>().Static(1); sp.Bind(lifetime, serverProtocol, SocketWireTest.Top); var cp = new RdSignal <int>().Static(1); cp.Bind(lifetime, clientProtocol, SocketWireTest.Top); var serverLog = new List <int>(); var clientLog = new List <int>(); sp.Advise(lifetime, i => serverLog.Add(i)); cp.Advise(lifetime, i => clientLog.Add(i)); //Connection is established for now sp.Fire(1); SpinWaitEx.SpinUntil(() => serverLog.Count == 1); SpinWaitEx.SpinUntil(() => clientLog.Count == 1); Assert.AreEqual(new List <int> { 1 }, serverLog); Assert.AreEqual(new List <int> { 1 }, clientLog); cp.Fire(2); SpinWaitEx.SpinUntil(() => serverLog.Count == 2); SpinWaitEx.SpinUntil(() => clientLog.Count == 2); Assert.AreEqual(new List <int> { 1, 2 }, serverLog); Assert.AreEqual(new List <int> { 1, 2 }, clientLog); proxy.StopServerToClientMessaging(); cp.Advise(lifetime, i => Assert.AreNotSame(3, i, "Value {0} mustn't be received", 3)); sp.Fire(3); SpinWaitEx.SpinUntil(() => serverLog.Count == 3); Assert.AreEqual(new List <int> { 1, 2, 3 }, serverLog); proxy.StopClientToServerMessaging(); sp.Advise(lifetime, i => Assert.AreNotSame(4, i, "Value {0} mustn't be received", 4)); cp.Fire(4); SpinWaitEx.SpinUntil(() => clientLog.Count == 3); Assert.AreEqual(new List <int> { 1, 2, 4 }, clientLog); //Connection is broken for now proxy.StartServerToClientMessaging(); sp.Fire(5); SpinWaitEx.SpinUntil(() => serverLog.Count == 4); SpinWaitEx.SpinUntil(() => clientLog.Count == 4); Assert.AreEqual(new List <int> { 1, 2, 3, 5 }, serverLog); Assert.AreEqual(new List <int> { 1, 2, 4, 5 }, clientLog); proxy.StartClientToServerMessaging(); cp.Fire(6); SpinWaitEx.SpinUntil(() => serverLog.Count == 5); SpinWaitEx.SpinUntil(() => clientLog.Count == 5); Assert.AreEqual(new List <int> { 1, 2, 3, 5, 6 }, serverLog); Assert.AreEqual(new List <int> { 1, 2, 4, 5, 6 }, clientLog); //Connection is established for now proxyLifetimeDefinition.Terminate(); cp.Advise(lifetime, i => Assert.AreNotSame(7, i, "Value {0} mustn't be received", 7)); sp.Fire(7); SpinWaitEx.SpinUntil(() => serverLog.Count == 6); Assert.AreEqual(new List <int> { 1, 2, 3, 5, 6, 7 }, serverLog); sp.Advise(lifetime, i => Assert.AreNotSame(8, i, "Value {0} mustn't be received", 8)); cp.Fire(8); SpinWaitEx.SpinUntil(() => clientLog.Count == 6); Assert.AreEqual(new List <int> { 1, 2, 4, 5, 6, 8 }, clientLog); //Connection is broken for now, proxy is not alive } }); }
protected Task Wait() { bool IsIdle(IRdDynamic p) => ((SingleThreadScheduler)p.Proto.Scheduler).IsIdle; return(Task.Run(() => SpinWaitEx.SpinUntil(() => IsIdle(ServerProtocol) && IsIdle(ClientProtocol)))); }