Пример #1
0
        public async Task Restart_DifferentCallback()
        {
            // Verify that we can restart a timer using the original interval
            // and a different callback.

            var ticks0 = 0;
            var ticks1 = 0;

            using (var timer = new AsyncTimer(
                       async() =>
            {
                ticks0++;
                await Task.CompletedTask;
            }))
            {
                Assert.False(timer.IsRunning);
                await Task.Delay(TimeSpan.FromSeconds(1));

                Assert.False(timer.IsRunning);
                Assert.Equal(0, ticks0);

                timer.Start(TimeSpan.FromSeconds(1));
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks0 == 5);

                timer.Stop();
                ticks0 = 0;
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks0 == 0);

                timer.Start(
                    callback: async() =>
                {
                    ticks1++;
                    await Task.CompletedTask;
                });
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks1 == 5);

                timer.Stop();
                ticks1 = 0;
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks1 == 0);
            }
        }
    public async Task Stop_waits_for_callback_to_complete()
    {
        var timer = new AsyncTimer();

        var callbackCompleted   = new TaskCompletionSource <bool>();
        var callbackTaskStarted = new TaskCompletionSource <bool>();

        timer.Start((time, token) =>
        {
            callbackTaskStarted.SetResult(true);
            return(callbackCompleted.Task);
        }, TimeSpan.Zero, e =>
        {
            //noop
        }, Task.Delay);

        await callbackTaskStarted.Task.ConfigureAwait(false);

        var stopTask  = timer.Stop();
        var delayTask = Task.Delay(1000);

        var firstToComplete = await Task.WhenAny(stopTask, delayTask).ConfigureAwait(false);

        Assert.AreEqual(delayTask, firstToComplete);
        callbackCompleted.SetResult(true);

        await stopTask.ConfigureAwait(false);
    }
Пример #3
0
        public async Task StartStop_DelayFirstTick()
        {
            var ticks = 0;

            // Verify that basic start/stop operations work when
            // delaying the first tick callback.

            using (var timer = new AsyncTimer(
                       async() =>
            {
                ticks++;
                await Task.CompletedTask;
            }))
            {
                Assert.False(timer.IsRunning);
                await Task.Delay(TimeSpan.FromSeconds(1));

                Assert.False(timer.IsRunning);
                Assert.Equal(0, ticks);

                timer.Start(TimeSpan.FromSeconds(1), delayFirstTick: true);
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 4);

                timer.Stop();
                ticks = 0;
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 0);
            }
        }
Пример #4
0
        public async Task StartStop()
        {
            // Verify that basic start/stop operations work.

            var ticks = 0;

            using (var timer = new AsyncTimer(
                       async() =>
            {
                ticks++;
                await Task.CompletedTask;
            }))
            {
                Assert.False(timer.IsRunning);
                await Task.Delay(TimeSpan.FromSeconds(1));

                Assert.Equal(TimeSpan.Zero, timer.Interval);
                Assert.False(timer.IsRunning);
                Assert.Equal(0, ticks);

                timer.Start(TimeSpan.FromSeconds(1));
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 5);
                Assert.Equal(TimeSpan.FromSeconds(1), timer.Interval);

                timer.Stop();
                ticks = 0;
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 0);
            }
        }
    public async Task Stop_cancels_token_while_waiting()
    {
        var timer         = new AsyncTimer();
        var waitCancelled = false;
        var delayStarted  = new TaskCompletionSource <bool>();

        timer.Start((time, token) =>
        {
            throw new Exception("Simulated!");
        }, TimeSpan.FromDays(7), e =>
        {
            //noop
        }, async(delayTime, token) =>
        {
            delayStarted.SetResult(true);
            try
            {
                await Task.Delay(delayTime, token).ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
                waitCancelled = true;
            }
        });
        await delayStarted.Task.ConfigureAwait(false);

        await timer.Stop().ConfigureAwait(false);

        Assert.IsTrue(waitCancelled);
    }
    public async Task Stop_cancels_token_while_in_callback()
    {
        var timer             = new AsyncTimer();
        var callbackCancelled = false;
        var callbackStarted   = new TaskCompletionSource <bool>();
        var stopInitiated     = new TaskCompletionSource <bool>();

        timer.Start(async(time, token) =>
        {
            callbackStarted.SetResult(true);
            await stopInitiated.Task.ConfigureAwait(false);
            if (token.IsCancellationRequested)
            {
                callbackCancelled = true;
            }
        }, TimeSpan.Zero, e =>
        {
            //noop
        }, Task.Delay);

        await callbackStarted.Task.ConfigureAwait(false);

        var stopTask = timer.Stop();

        stopInitiated.SetResult(true);
        await stopTask.ConfigureAwait(false);

        Assert.IsTrue(callbackCancelled);
    }
Пример #7
0
    public async Task Stop_cancels_token_while_in_callback()
    {
        var timer            = new AsyncTimer();
        var callbackCanceled = false;
        var callbackStarted  = new TaskCompletionSource <bool>();
        var stopInitiated    = new TaskCompletionSource <bool>();

        timer.Start(
            callback: async(_, token) =>
        {
            callbackStarted.SetResult(true);
            await stopInitiated.Task;
            if (token.IsCancellationRequested)
            {
                callbackCanceled = true;
            }
        },
            interval: TimeSpan.Zero,
            errorCallback: _ =>
        {
            //noop
        },
            delayStrategy: Task.Delay);

        await callbackStarted.Task;
        var stopTask = timer.Stop();

        stopInitiated.SetResult(true);
        await stopTask;

        Assert.True(callbackCanceled);
    }
Пример #8
0
    public async Task Stop_cancels_token_while_waiting()
    {
        var timer        = new AsyncTimer();
        var waitCanceled = false;
        var delayStarted = new TaskCompletionSource <bool>();

        timer.Start(
            callback: (_, _) => throw new Exception("Simulated!"),
            interval: TimeSpan.FromDays(7),
            errorCallback: _ =>
        {
            // noop
        },
            delayStrategy: async(delayTime, token) =>
        {
            delayStarted.SetResult(true);
            try
            {
                await Task.Delay(delayTime, token);
            }
            catch (OperationCanceledException)
            {
                waitCanceled = true;
            }
        });
        await delayStarted.Task;
        await timer.Stop();

        Assert.True(waitCanceled);
    }
Пример #9
0
    public async Task Stop_waits_for_callback_to_complete()
    {
        var timer = new AsyncTimer();

        var callbackCompleted   = new TaskCompletionSource <bool>();
        var callbackTaskStarted = new TaskCompletionSource <bool>();

        timer.Start(
            callback: (_, _) =>
        {
            callbackTaskStarted.SetResult(true);
            return(callbackCompleted.Task);
        },
            interval: TimeSpan.Zero,
            errorCallback: _ =>
        {
            //noop
        },
            delayStrategy: Task.Delay);

        await callbackTaskStarted.Task;

        var stopTask  = timer.Stop();
        var delayTask = Task.Delay(1000);

        var firstToComplete = await Task.WhenAny(stopTask, delayTask);

        Assert.Equal(delayTask, firstToComplete);
        callbackCompleted.SetResult(true);

        await stopTask;
    }
Пример #10
0
        public async Task Restart_DifferentInterval()
        {
            // Verify that we can restart a timer using a different interval
            // and also delaying the first tick.

            var ticks = 0;

            using (var timer = new AsyncTimer(
                       async() =>
            {
                ticks++;
                await Task.CompletedTask;
            }))
            {
                Assert.False(timer.IsRunning);
                await Task.Delay(TimeSpan.FromSeconds(1));

                Assert.False(timer.IsRunning);
                Assert.Equal(0, ticks);

                timer.Start(TimeSpan.FromSeconds(1));
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 5);

                timer.Stop();
                ticks = 0;
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 0);

                timer.Start(TimeSpan.FromSeconds(2), delayFirstTick: true);
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 2);

                timer.Stop();
                ticks = 0;
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 0);
            }
        }
Пример #11
0
        public async Task Restart_SameInterval()
        {
            // Verify that we can restart a timer using the original interval.

            var ticks = 0;

            using (var timer = new AsyncTimer(
                       async() =>
            {
                ticks++;
                await Task.CompletedTask;
            }))
            {
                Assert.False(timer.IsRunning);
                await Task.Delay(TimeSpan.FromSeconds(1));

                Assert.False(timer.IsRunning);
                Assert.Equal(0, ticks);

                timer.Start(TimeSpan.FromSeconds(1));
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 5);

                timer.Stop();
                ticks = 0;
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 0);

                timer.Start();
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 5);

                timer.Stop();
                ticks = 0;
                await Task.Delay(TimeSpan.FromSeconds(4.5));

                Assert.True(ticks == 0);
            }
        }
Пример #12
0
 public void Stop()
 {
     paused = false;
     if (_tcpServer != null)
     {
         _tcpServer.Stop();
         _tcpServer = null;
     }
     DateTimeService.Instance.HourChanged -= OnHourChanged;
     if (_scanTimer != null)
     {
         _scanTimer.Stop();
         _scanTimer.Dispose();
         _scanTimer = null;
     }
 }
        private async void CopyFilesAsyncButton_Click(object sender, EventArgs e)
        {
            if (CopyFilesAsyncButton.Text.Equals(copyFilesAsyncText))
            {
                string sourceDirectory      = @"C:\Users\barry\Source\Repos\CSharp-7-and-DotNET-Core-Cookbook-master\Chapter6\AsyncSource";
                string destinationDirectory = @"C:\Users\barry\Source\Repos\CSharp-7-and-DotNET-Core-Cookbook-master\Chapter6\AsyncDestination";
                CopyFilesAsyncButton.Text = cancelAsyncCopyText;
                cancellationTokenSource   = new CancellationTokenSource();
                elapsedTime = 0;
                AsyncTimer.Start();

                IEnumerable <string> fileEntries = Directory.EnumerateFiles(sourceDirectory);
                foreach (string sourceFile in fileEntries)
                {
                    using (FileStream sourceFileStream = File.Open(sourceFile, FileMode.Open))
                    {
                        string destinationFilePath = $"{destinationDirectory}{Path.GetFileName(sourceFile)}";
                        using (FileStream destinationFileStream = File.Create(destinationFilePath))
                        {
                            try
                            {
                                await sourceFileStream.CopyToAsync(destinationFileStream, 81920, cancellationTokenSource.Token);
                            }
                            catch (OperationCanceledException)
                            {
                                AsyncTimer.Stop();
                                TimerLabel.Text = $"Cancelled after {elapsedTime} seconds";
                            }
                        }
                    }
                }
            }
            if (!cancellationTokenSource.IsCancellationRequested)
            {
                AsyncTimer.Stop();
                TimerLabel.Text = $"Completed in {elapsedTime} seconds";
            }
            if (CopyFilesAsyncButton.Text.Equals(cancelAsyncCopyText))
            {
                CopyFilesAsyncButton.Text = copyFilesAsyncText;
                Debug.Assert(cancellationTokenSource != null);
                cancellationTokenSource.Cancel();
            }
        }
Пример #14
0
        public void Errors()
        {
            // Check error detection.

            var timer = new AsyncTimer(async() => await Task.CompletedTask);

            Assert.Throws <ArgumentException>(() => timer.Start(TimeSpan.FromSeconds(-1)));
            Assert.Throws <InvalidOperationException>(() => timer.Start());

            timer.Dispose();

            Assert.Throws <ObjectDisposedException>(() => timer.Start(TimeSpan.FromSeconds(1)));
            Assert.Throws <ObjectDisposedException>(() => timer.Stop());

            timer = new AsyncTimer();

            Assert.Throws <InvalidOperationException>(() => timer.Start(TimeSpan.FromSeconds(1)));
            timer.Dispose();
        }
Пример #15
0
        /// <summary>
        /// Disconnects the client
        /// </summary>
        /// <param name="disconnecting">if <c>true</c>, the function won't call Socket.Disconnect</param>
        public void Disconnect(bool disconnecting = false)
        {
            lock (this)
            {
                if (!disconnecting)
                {
                    m_SocketContext.Disconnect();
                }

                if (!m_blDisconnected)
                {
                    if (m_PingTimer.IsRunning)
                    {
                        m_PingTimer.Stop();
                    }
                    m_blDisconnected = true;
                }
            }
        }
Пример #16
0
        public void StopMovement(bool packet = false)
        {
            lock (m_lock)
            {
                if (m_movementType == MovementType.Moving)
                {
                    if (m_movementTimer.IsRunning)
                    {
                        m_movementTimer.Stop();
                    }
                    Vector3 old_pos = m_position;
                    m_position = (m_position.ToVector2() + m_direction * this.Speed * (Environment.TickCount - m_lastMovementUpdate) / 1000f).ToVector3(m_position.Y);
                    Vector3 result;
                    if (Data.NavMesh.Collision.Test(m_region, old_pos, m_position, out result))
                    {
                        m_position = old_pos;
                        Logging.Log()("collision detected 3", LogLevel.Info);
                    }
                    UpdatePosition();
                }

                if (packet)
                {
                    Packet pkt = new Packet(SCommon.Opcode.Agent.GAMEOBJECT_WARP);
                    pkt.WriteInt32(m_uniqueId);
                    pkt.WriteInt16(m_region);
                    pkt.WriteSingle(m_position.X);
                    pkt.WriteSingle(m_position.Y);
                    pkt.WriteSingle(m_position.Z);
                    pkt.WriteUInt16(m_angle);
                    SendPacket(pkt);
                    BroadcastToSightList(pkt);
                }

                m_movementType     = MovementType.NotMoving;
                m_hasDestination   = false;
                m_hasAngleMovement = false;
                m_direction        = Vector2.Zero;
            }
        }
Пример #17
0
        /// <summary>
        /// Disconnects the client
        /// </summary>
        /// <param name="disconnecting">if <c>true</c>, the function won't call Socket.Disconnect</param>
        public void Disconnect(bool disconnecting = false)
        {
            lock (this)
            {
                if (!disconnecting)
                {
                    m_SocketContext.Disconnect();
                }

                if (!m_blDisconnected)
                {
                    Globals.GlobalDB.ExecuteCommandAsync("DELETE FROM _ActiveSessions WHERE UserSID = {0}", m_AccountInfo.SID);

                    if (m_PingTimer.IsRunning)
                    {
                        m_PingTimer.Stop();
                    }

                    if (m_Character != null && m_Character.m_isIngame)
                    {
                        lock (m_Character.m_lock)
                        {
                            if (m_Character.m_movementTimer.IsRunning)
                            {
                                m_Character.m_movementTimer.Stop();
                            }
                        }
                        m_Character.Disappear(false);
                        Globals.ShardDB.ExecuteCommandAsync(String.Format("UPDATE _Char SET LatestRegion = {0}, PosX = {1}, PosY = {2}, PosZ = {3} WHERE CharID = {4}", m_Character.m_region, m_Character.m_position.X, m_Character.m_position.Y, m_Character.m_position.Z, m_Character.m_charId));
                    }

                    m_Character = null;
                    m_AccountInfo.Characters = null;
                    m_AccountInfo            = default(AccountInfo);

                    m_blDisconnected = true;
                }
            }
        }
Пример #18
0
 public Task Stop()
 {
     return(updateTimer.Stop());
 }