public void RegisterTask_AsynchronousCompletion_SwallowsExceptionsThrownByEndDelegate() {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);
            bool endDelegateWasCalled = false;

            ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */);

            Func<AsyncCallback, IAsyncResult> beginDelegate = callback => {
                MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);
                ThreadPool.QueueUserWorkItem(_ => {
                    callback(asyncResult);
                    waitHandle.Set();
                });
                return asyncResult;
            };
            Action<IAsyncResult> endDelegate = delegate {
                endDelegateWasCalled = true;
                throw new Exception("This is a sample exception.");
            };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);
            waitHandle.WaitOne();

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }
예제 #2
0
        public void OutstandingOperationsProperty() {
            // Act
            AsyncManager helper = new AsyncManager();

            // Assert
            Assert.IsNotNull(helper.OutstandingOperations);
        }
예제 #3
0
        public void ParametersProperty() {
            // Act
            AsyncManager helper = new AsyncManager();

            // Assert
            Assert.IsNotNull(helper.Parameters);
        }
        public void RegisterTask_AsynchronousCompletion() {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);
            bool endDelegateWasCalled = false;

            ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */);

            Func<AsyncCallback, IAsyncResult> beginDelegate = callback => {
                Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter was not incremented properly.");
                MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);
                ThreadPool.QueueUserWorkItem(_ => {
                    Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter shouldn't have been decremented yet.");
                    callback(asyncResult);
                    waitHandle.Set();
                });
                return asyncResult;
            };
            Action<IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);
            waitHandle.WaitOne();

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.IsTrue(syncContext.SendWasCalled, "Asynchronous call to End() should have been routed through SynchronizationContext.Send()");
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }
예제 #5
0
        public void FinishEvent_ExplicitCallToFinishMethod() {
            // Arrange
            AsyncManager helper = new AsyncManager();

            bool delegateCalled = false;
            helper.Finished += delegate { delegateCalled = true; };

            // Act
            helper.Finish();

            // Assert
            Assert.IsTrue(delegateCalled);
        }
예제 #6
0
        public void FinishEvent_LinkedToOutstandingOperationsCompletedEvent() {
            // Arrange
            AsyncManager helper = new AsyncManager();

            bool delegateCalled = false;
            helper.Finished += delegate { delegateCalled = true; };

            // Act
            helper.OutstandingOperations.Increment();
            helper.OutstandingOperations.Decrement();

            // Assert
            Assert.IsTrue(delegateCalled);
        }
예제 #7
0
        public void TimeoutProperty() {
            // Arrange
            int setValue = 50;
            AsyncManager helper = new AsyncManager();

            // Act
            int defaultTimeout = helper.Timeout;
            helper.Timeout = setValue;
            int newTimeout = helper.Timeout;

            // Assert
            Assert.AreEqual(45000, defaultTimeout);
            Assert.AreEqual(setValue, newTimeout);
        }
예제 #8
0
        public void Sync()
        {
            // Arrange
            Mock<SynchronizationContext> mockSyncContext = new Mock<SynchronizationContext>();
            mockSyncContext
                .Setup(c => c.Send(It.IsAny<SendOrPostCallback>(), null))
                .Callback(
                    delegate(SendOrPostCallback d, object state) { d(state); });

            AsyncManager helper = new AsyncManager(mockSyncContext.Object);
            bool wasCalled = false;

            // Act
            helper.Sync(() => { wasCalled = true; });

            // Assert
            Assert.True(wasCalled);
        }
예제 #9
0
        public void Sync()
        {
            // Arrange
            Mock <SynchronizationContext> mockSyncContext = new Mock <SynchronizationContext>();

            mockSyncContext
            .Setup(c => c.Send(It.IsAny <SendOrPostCallback>(), null))
            .Callback(
                delegate(SendOrPostCallback d, object state) { d(state); });

            AsyncManager helper    = new AsyncManager(mockSyncContext.Object);
            bool         wasCalled = false;

            // Act
            helper.Sync(() => { wasCalled = true; });

            // Assert
            Assert.True(wasCalled);
        }
예제 #10
0
        public void DateAsync()
        {
            AsyncManager.OutstandingOperations.Increment();

            var random = new Random();

            var sleep = random.Next(5, 20);

            var date = DateTime.Now.ToString();

            AsyncManager.Sync(() =>
            {
                Thread.Sleep(sleep * 1000);

                AsyncManager.Parameters["date"] = date;

                AsyncManager.OutstandingOperations.Decrement();
            });
        }
예제 #11
0
        void Finding(object sender, FindingWidgetEventArgs e)
        {
            if ((!e.Id.HasValue || e.Id <= 0) && String.IsNullOrEmpty(e.Name))
            {
                return;
            }

            if (e.Id.HasValue && e.Id > 0)
            {
                AsyncManager.RegisterAsyncTask(
                    (asyncSender, ea, callback, state) => // Begin
                    widgetRepository.BeginFind(e.Id.Value, callback, state),
                    result =>                             // End
                {
                    var widget = widgetRepository.EndFind(result);
                    if (widget != null)
                    {
                        View.Model.Widgets.Add(widget);
                    }
                },
                    result => { }, // Timeout
                    null, false);
            }
            else
            {
                AsyncManager.RegisterAsyncTask(
                    (asyncSender, ea, callback, state) => // Begin
                    widgetRepository.BeginFindByName(e.Name, callback, state),
                    result =>                             // End
                {
                    var widget = widgetRepository.EndFindByName(result);
                    if (widget != null)
                    {
                        View.Model.Widgets.Add(widget);
                    }
                },
                    result => { }, // Timeout
                    null, false);
            }
            AsyncManager.ExecuteRegisteredAsyncTasks();
            View.Model.ShowResults = true;
        }
        public void RegisterTask_AsynchronousCompletion_SwallowsExceptionsThrownByEndDelegate()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager         = new AsyncManager(syncContext);
            bool         endDelegateWasCalled = false;

            using (
                ManualResetEvent waitHandle = new ManualResetEvent(
                    false /* initialState */
                    )
                )
            {
                Func <AsyncCallback, IAsyncResult> beginDelegate = callback =>
                {
                    MockAsyncResult asyncResult = new MockAsyncResult(
                        false /* completedSynchronously */
                        );
                    ThreadPool.QueueUserWorkItem(
                        _ =>
                    {
                        callback(asyncResult);
                        waitHandle.Set();
                    }
                        );
                    return(asyncResult);
                };
                Action <IAsyncResult> endDelegate = delegate
                {
                    endDelegateWasCalled = true;
                    throw new Exception("This is a sample exception.");
                };

                // Act
                asyncManager.RegisterTask(beginDelegate, endDelegate);
                waitHandle.WaitOne();

                // Assert
                Assert.True(endDelegateWasCalled);
                Assert.Equal(0, asyncManager.OutstandingOperations.Count);
            }
        }
예제 #13
0
            public async Task Task_With_Transform_Is_Other_Result()
            {
                //Arrange
                var functions    = new Mock <Functions>();
                var namespaceCtx = new IntPtr(37);

                functions.Setup(f => f.PrjCompleteCommand(namespaceCtx, 1, HRESULT.S_FALSE, IntPtr.Zero));
                var tcs    = new TaskCompletionSource <int>();
                var target = new AsyncManager(functions.Object);

                //Act
                var hr = target.ProcessCommandPossibleAsync(namespaceCtx, 1, (cts) => tcs.Task, (value) => HRESULT.S_FALSE);

                tcs.SetResult(4);
                await Task.Delay(50);

                //Assert
                Assert.Equal(HRESULT.ERROR_IO_PENDING, hr);
                functions.VerifyAll();
            }
예제 #14
0
            public async Task Direct_Task_Transform_With_Error_In_Transform_Is_Error()
            {
                //Arrange
                var functions    = new Mock <Functions>();
                var namespaceCtx = new IntPtr(37);

                functions.Setup(f => f.PrjCompleteCommand(namespaceCtx, 1, HRESULT.E_INVALIDARG, IntPtr.Zero));
                var tcs    = new TaskCompletionSource <int>();
                var target = new AsyncManager(functions.Object);

                //Act
                var hr = target.ProcessCommandPossibleAsync <int>(namespaceCtx, 1, (cts) => tcs.Task, (value) => throw new Exception());

                tcs.SetResult(4);
                await Task.Delay(50);

                //Assert
                Assert.Equal(HRESULT.ERROR_IO_PENDING, hr);
                functions.VerifyAll();
            }
예제 #15
0
            public async Task Direct_ValueTask_No_Transform_Is_Error()
            {
                //Arrange
                var functions    = new Mock <Functions>();
                var namespaceCtx = new IntPtr(37);

                functions.Setup(f => f.PrjCompleteCommand(namespaceCtx, 1, HRESULT.E_INVALIDARG, IntPtr.Zero));
                var tcs    = new TaskCompletionSource <NotificationRequired>();
                var target = new AsyncManager(functions.Object);

                //Act
                var hr = target.ProcessCommandPossibleAsync(namespaceCtx, 1, (Func <CancellationTokenSource, ValueTask>)((cts) => new ValueTask(tcs.Task)));

                tcs.SetException(new Exception());
                await Task.Delay(50);

                //Assert
                Assert.Equal(HRESULT.ERROR_IO_PENDING, hr);
                functions.VerifyAll();
            }
        public void RegisterTask_ResetsOutstandingOperationCountIfBeginMethodThrows() {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);

            Func<AsyncCallback, IAsyncResult> beginDelegate = cb => {
                throw new InvalidOperationException("BeginDelegate throws.");
            };
            Action<IAsyncResult> endDelegate = ar => {
                Assert.Fail("This should never be called.");
            };

            // Act & assert
            ExceptionHelper.ExpectInvalidOperationException(
                delegate {
                    asyncManager.RegisterTask(beginDelegate, endDelegate);
                }, "BeginDelegate throws.");

            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count);
        }
        // Load level from the given assetBundle.
        public static ITask LoadLevelAsync(string assetBundleName, string levelName, LoadSceneMode loadMode = LoadSceneMode.Single)
        {
            log.Info("Loading {0} from {1} bundle...", levelName, assetBundleName);

#if UNITY_EDITOR
            if (SimulateAssetBundleInEditor)
            {
                string[] levelPaths = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(assetBundleName, levelName);
                if (levelPaths.Length == 0)
                {
                    //TODO: The error needs to differentiate that an asset bundle name doesn't exist from that there right scene does not exist in the asset bundle...
                    return(Task.FromError(new Exception("There is no scene with name \"" + levelName + "\" in " + assetBundleName)));
                }
                return(AsyncManager.AddOperation(SceneManager.LoadSceneAsync(levelPaths[0], loadMode)));
            }
#endif
            return(RemapVariantName(assetBundleName)
                   .Then(bundleName => LoadAssetBundleAsync(bundleName))
                   .Then(bundle => AsyncManager.AddOperation(SceneManager.LoadSceneAsync(levelName, loadMode))));
        }
예제 #18
0
            public void BasicUsageSound()
            {
                //Arrange
                var functions    = new Mock <Functions>();
                var namespaceCtx = new IntPtr(37);
                var target       = new AsyncManager(functions.Object);

                //Act
                var  cts = target.GetCancellationTokenForCommand(99);
                bool cancellationCalled = false;

                cts.Token.Register(() =>
                {
                    cancellationCalled = true;
                });
                target.ProcessCancelCommand(99);

                //Assert
                Assert.True(cancellationCalled);
            }
예제 #19
0
        public void RegisterTask_ResetsOutstandingOperationCountIfBeginMethodThrows()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);

            Func <AsyncCallback, IAsyncResult> beginDelegate = cb => {
                throw new InvalidOperationException("BeginDelegate throws.");
            };
            Action <IAsyncResult> endDelegate = ar => {
                Assert.Fail("This should never be called.");
            };

            // Act & assert
            ExceptionHelper.ExpectInvalidOperationException(
                delegate {
                asyncManager.RegisterTask(beginDelegate, endDelegate);
            }, "BeginDelegate throws.");

            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count);
        }
예제 #20
0
            public async Task Indirect_Task_With_NotificationMask_Is_Error()
            {
                //Arrange
                var functions    = new Mock <Functions>();
                var namespaceCtx = new IntPtr(37);

                functions.Setup(f => f.PrjCompleteCommand(namespaceCtx, 1, HRESULT.E_INVALIDARG, IntPtr.Zero));
                var tcs    = new TaskCompletionSource <NotificationRequired>();
                var target = new AsyncManager(functions.Object);
                var parms  = new PRJ_NOTIFICATION_PARAMETERS();

                //Act
                var hr = target.ProcessCommandPossibleAsyncWithNotificationMask(namespaceCtx, 1, (cts) => tcs.Task, parms);

                tcs.SetException(new Exception());
                await Task.Delay(50);

                //Assert
                Assert.Equal(HRESULT.ERROR_IO_PENDING, hr);
                functions.VerifyAll();
            }
예제 #21
0
        void Load(object sender, EventArgs e)
        {
            View.Model.Messages.Add(ThreadMessage("View.Load event handled"));

            AsyncManager.RegisterAsyncTask(
                (asyncSender, ea, callback, state) => // Begin
            {
                View.Model.Messages.Add(ThreadMessage("Async task doStuff1 begin handler"));
                return(doStuff1.BeginInvoke(callback, state));
            },
                result => // End
            {
                var msg = doStuff1.EndInvoke(result);
                View.Model.Messages.Add(msg);
                View.Model.Messages.Add(ThreadMessage("Async task doStuff1 end handler"));
            },
                result => // Timeout
                View.Model.Messages.Add(ThreadMessage("Async task doStuff1 timeout handler")),
                null,
                true
                );

            AsyncManager.RegisterAsyncTask(
                (asyncSender, ea, callback, state) => // Begin
            {
                View.Model.Messages.Add(ThreadMessage("Async task doStuff2 begin handler"));
                return(doStuff2.BeginInvoke(callback, state));
            },
                result => // End
            {
                var msg = doStuff2.EndInvoke(result);
                View.Model.Messages.Add(msg);
                View.Model.Messages.Add(ThreadMessage("Async task doStuff2 end handler"));
            },
                result => // Timeout
                View.Model.Messages.Add(ThreadMessage("Async task doStuff2 timeout handler")),
                null,
                true
                );
        }
        TResult ExecuteLockAction <TResult>(Func <Microsoft.Build.Evaluation.Project, TResult> callback, LockType lockType = LockType.Read, TResult defaultValue = default(TResult))
        {
            var context = ContainingProject as IVsBrowseObjectContext;

            if (context == null)
            {
                context = ContainingProject.Object as IVsBrowseObjectContext;
            }

            if (context != null)
            {
                return(AsyncManager.Run(async() =>
                {
                    if (lockType == LockType.Read)
                    {
                        using (var access = await ProjectLockService.ReadLockAsync())
                        {
                            var configuredProject = await context.UnconfiguredProject.GetSuggestedConfiguredProjectAsync();

                            var project = await access.GetProjectAsync(configuredProject);

                            return callback(project);
                        }
                    }
                    else
                    {
                        using (var access = await ProjectLockService.WriteLockAsync())
                        {
                            var configuredProject = await context.UnconfiguredProject.GetSuggestedConfiguredProjectAsync();

                            var project = await access.GetProjectAsync(configuredProject);

                            return callback(project);
                        }
                    }
                }));
            }

            return(defaultValue);
        }
예제 #23
0
        public RemoteManager(MainService main)
        {
            Main         = main;
            AsyncManager = new AsyncManager(Run);

            try
            {
                var sodium = RuntimeInformation.ProcessArchitecture.ToString().ToLower() + "\\libsodium.dll";
                if (!File.Exists(sodium))
                {
                    Main.LogManager.Log(LogManager.CATEGORY_SERVICE_ERROR, Tag, "未找到架构匹配的 libsodium, 当前系统可能不支持远程管理");
                }
                else if (NTAPI.LoadLibraryEx(Path.GetFullPath(sodium), IntPtr.Zero, 0) == IntPtr.Zero)
                {
                    Main.LogManager.Log(LogManager.CATEGORY_SERVICE_ERROR, Tag, "libsodium 加载失败, 远程管理无法正常工作");
                }
            }
            catch (Exception e)
            {
                Main.LogManager.Log(LogManager.CATEGORY_SERVICE_ERROR, Tag, "libsodium 加载失败, 远程管理无法正常工作: " + e.ToString());
            }
        }
예제 #24
0
            public async Task Task_With_NotificationMask_Is_S_OK()
            {
                //Arrange
                var functions    = new Mock <Functions>();
                var namespaceCtx = new IntPtr(37);

                functions.Setup(f => f.PrjCompleteCommand(namespaceCtx, 1, HRESULT.S_OK, It.IsAny <IntPtr>()));
                var tcs    = new TaskCompletionSource <NotificationRequired>();
                var target = new AsyncManager(functions.Object);

                var parms = new PRJ_NOTIFICATION_PARAMETERS();

                //Act
                var hr = target.ProcessCommandPossibleAsyncWithNotificationMask(namespaceCtx, 1, (cts) => tcs.Task, parms);

                tcs.SetResult(NotificationRequired.FileCreated);
                await Task.Delay(50);

                //Assert
                Assert.Equal(HRESULT.ERROR_IO_PENDING, hr);
                Assert.Equal(PRJ_NOTIFY_TYPES.PRJ_NOTIFY_NONE, parms.NotificationMask);
                functions.VerifyAll();
            }
예제 #25
0
        public void RegisterTask_SynchronousCompletion()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager         = new AsyncManager(syncContext);
            bool         endDelegateWasCalled = false;

            Func <AsyncCallback, IAsyncResult> beginDelegate = callback => {
                Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter was not incremented properly.");
                MockAsyncResult asyncResult = new MockAsyncResult(true /* completedSynchronously */);
                callback(asyncResult);
                return(asyncResult);
            };
            Action <IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.IsFalse(syncContext.SendWasCalled, "Synchronous call to End() should not have been routed through SynchronizationContext.Send()");
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }
        public void RegisterTask_SynchronousCompletion()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager         = new AsyncManager(syncContext);
            bool         endDelegateWasCalled = false;

            Func <AsyncCallback, IAsyncResult> beginDelegate = callback =>
            {
                Assert.Equal(1, asyncManager.OutstandingOperations.Count);
                MockAsyncResult asyncResult = new MockAsyncResult(true /* completedSynchronously */);
                callback(asyncResult);
                return(asyncResult);
            };
            Action <IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);

            // Assert
            Assert.True(endDelegateWasCalled);
            Assert.False(syncContext.SendWasCalled);
            Assert.Equal(0, asyncManager.OutstandingOperations.Count);
        }
예제 #27
0
        public void RegisterTaskWithFunc()
        {
            // Arrange
            Func <int>      numCallsFunc;
            AsyncManager    helper         = GetAsyncManagerForRegisterTask(out numCallsFunc);
            MockAsyncResult asyncResult    = new MockAsyncResult();
            AsyncCallback   storedCallback = null;

            int opCountDuringBeginDelegate = 0;
            int opCountDuringEndDelegate   = 0;

            Func <AsyncCallback, IAsyncResult> beginDelegate = innerCb => {
                storedCallback             = innerCb;
                opCountDuringBeginDelegate = helper.OutstandingOperations.Count;
                return(asyncResult);
            };
            AsyncCallback endDelegate = ar => {
                Assert.AreEqual(asyncResult, ar);
                opCountDuringEndDelegate = helper.OutstandingOperations.Count;
            };

            // Act
            int          opCountBeforeBeginDelegate = helper.OutstandingOperations.Count;
            IAsyncResult returnedAsyncResult        = helper.RegisterTask(beginDelegate, endDelegate);

            storedCallback(returnedAsyncResult);
            int opCountAfterEndDelegate = helper.OutstandingOperations.Count;

            // Assert
            Assert.AreEqual(asyncResult, returnedAsyncResult);
            Assert.AreEqual(0, opCountBeforeBeginDelegate);
            Assert.AreEqual(1, opCountDuringBeginDelegate);
            Assert.AreEqual(1, opCountDuringEndDelegate);
            Assert.AreEqual(0, opCountAfterEndDelegate);
            Assert.AreEqual(1, numCallsFunc(), "Send() was not called.");
        }
예제 #28
0
 public void SetUp()
 {
     mgr = new AsyncManager(mdf);
 }
예제 #29
0
        private void Load(object sender, EventArgs e)
        {
            View.Model.RecordViewLoad();

            AsyncManager.RegisterAsyncTask(InvokeAsync);
        }
예제 #30
0
        private void OnUpdate()
        {
            if (serverState == ServerState.Unloaded)
            {
                return;
            }

            Time.FrameTick(false, false);

            AsyncManager.InvokeBeforeUpdate();

            Scene.Current.Update();

            AsyncManager.InvokeAfterUpdate();

            DualityApp.RunCleanup();

            lock (sync) {
                // Respawn dead players immediately
                if (playerSpawningEnabled)
                {
                    foreach (KeyValuePair <NetConnection, PlayerClient> pair in players)
                    {
                        if (pair.Value.State == PlayerState.Dead)
                        {
                            RespawnPlayer(pair.Value);
                        }
                    }
                }

                if (serverState == ServerState.LevelReady)
                {
                    if (players.Count >= minPlayers)
                    {
                        countdown -= Time.DeltaTime;

                        if (countdown <= 0f)
                        {
                            serverState     = ServerState.LevelRunning;
                            countdownNotify = 0;

                            levelStartTime = NetTime.Now;

                            SendToActivePlayers(new PlayerSetControllable {
                                IsControllable = true
                            }, 3, NetDeliveryMethod.ReliableUnordered, PacketChannels.UnorderedUpdates);

                            SendToActivePlayers(new ShowMessage {
                                Flags = 0x01,
                                Text  = "\n\n\n\f[c:1]Go!"
                            }, 24, NetDeliveryMethod.ReliableUnordered, PacketChannels.UnorderedUpdates);
                        }
                        else if (countdown < countdownNotify)
                        {
                            countdownNotify = (int)Math.Ceiling(countdown);

                            if (countdownNotify == 15)
                            {
                                SendToActivePlayers(new ShowMessage {
                                    Text = "\n\n\n\f[c:1]Game will start in 15 seconds!"
                                }, 48, NetDeliveryMethod.ReliableUnordered, PacketChannels.UnorderedUpdates);
                            }
                            else if (countdownNotify == 3)
                            {
                                SendToActivePlayers(new ShowMessage {
                                    Flags = 0x01,
                                    Text  = "\n\n\n\f[c:4]3"
                                }, 24, NetDeliveryMethod.ReliableUnordered, PacketChannels.UnorderedUpdates);
                            }
                            else if (countdownNotify == 2)
                            {
                                SendToActivePlayers(new ShowMessage {
                                    Flags = 0x01,
                                    Text  = "\n\n\n\f[c:3]2"
                                }, 24, NetDeliveryMethod.ReliableUnordered, PacketChannels.UnorderedUpdates);
                            }
                            else if (countdownNotify == 1)
                            {
                                SendToActivePlayers(new ShowMessage {
                                    Flags = 0x01,
                                    Text  = "\n\n\n\f[c:2]1"
                                }, 24, NetDeliveryMethod.ReliableUnordered, PacketChannels.UnorderedUpdates);
                            }
                        }
                    }
                }
                else if (serverState == ServerState.LevelComplete)
                {
                    countdown -= Time.DeltaTime;

                    if (countdown <= 0f)
                    {
                        if (activePlaylist == null)
                        {
                            ChangeLevel(currentLevel, currentLevelType);
                        }
                        else
                        {
                            ChangeLevelFromPlaylist(activePlaylistIndex + 1);
                        }
                    }
                }

                // Update all players
                if (playerConnections.Count > 0)
                {
                    List <ActorBase> spawnedActors = levelHandler.SpawnedActors;

                    int playerCount       = players.Count;
                    int spawnedActorCount = spawnedActors.Count;

                    NetOutgoingMessage m = server.CreateMessage(14 + 21 * playerCount + 24 * spawnedActorCount);
                    m.Write(SpecialPacketTypes.UpdateAllActors);
                    m.Write((long)(NetTime.Now * 1000));

                    foreach (KeyValuePair <NetConnection, PlayerClient> pair in players)
                    {
                        PlayerClient player = pair.Value;
                        m.Write((int)player.Index); // Player Index

                        if (player.State != PlayerState.Spawned || !player.ProxyActor.IsVisible)
                        {
                            m.Write((byte)0x00); // Flags - None
                            continue;
                        }

                        m.Write((byte)0x01); // Flags - Visible

                        Vector3 pos = player.ProxyActor.Transform.Pos;
                        m.Write((ushort)(pos.X * 2.5f));
                        m.Write((ushort)(pos.Y * 2.5f));
                        m.Write((ushort)(pos.Z * 2.5f));

                        m.Write((bool)player.ProxyActor.IsFacingLeft);
                    }

                    foreach (ActorBase actor in spawnedActors)
                    {
                        if ((actor.CollisionFlags & CollisionFlags.TransformChanged) == 0)
                        {
                            continue;
                        }

                        actor.CollisionFlags &= ~CollisionFlags.TransformChanged;

                        m.Write((int)actor.Index); // Object Index

                        if (!actor.IsVisible)
                        {
                            m.Write((byte)0x00); // Flags - None
                            continue;
                        }

                        if (actor.Transform.Scale > 0.95f && actor.Transform.Scale < 1.05f &&
                            actor.Transform.Angle > -0.04f && actor.Transform.Angle < 0.04f)
                        {
                            m.Write((byte)0x01); // Flags - Visible

                            Vector3 pos = actor.Transform.Pos;
                            m.Write((ushort)(pos.X * 2.5f));
                            m.Write((ushort)(pos.Y * 2.5f));
                            m.Write((ushort)(pos.Z * 2.5f));

                            m.Write((bool)actor.IsFacingLeft);
                        }
                        else
                        {
                            m.Write((byte)0x03); // Flags - Visible | HasScaleAngle

                            Vector3 pos = actor.Transform.Pos;
                            m.Write((ushort)pos.X);
                            m.Write((ushort)pos.Y);
                            m.Write((ushort)pos.Z);

                            m.Write((float)actor.Transform.Scale);
                            m.WriteRangedSingle((float)actor.Transform.Angle, 0f, MathF.TwoPi, 8);

                            m.Write((bool)actor.IsFacingLeft);
                        }
                    }

                    m.Write((int)-1); // Terminator

                    // Send update command to all active players
                    server.Send(m, playerConnections, NetDeliveryMethod.Unreliable, PacketChannels.UnorderedUpdates);
                }
            }
        }
예제 #31
0
        private static readonly Dictionary <string, LoadResourcesAssetRecord> mAllLoadResourcesAssetRecords = new Dictionary <string, LoadResourcesAssetRecord>(200); //Cache 所有加载的资源


        #region 计时器删除无效资源
        static LocalResourcesManager()
        {
            AsyncManager.InvokeRepeating(0, s_FullCheckTimeInterval, FullCheckUnReferenceAset);
        }
예제 #32
0
        private void Load(object sender, EventArgs e)
        {
            View.Model.Append("View Load");

            AsyncManager.RegisterAsyncTask(RunTasks);
        }
예제 #33
0
        /// <summary>
        /// Initializes the part of Duality that requires a valid rendering context.
        /// Should be called before performing any rendering related operations with Duality.
        /// Is called implicitly when using <see cref="OpenWindow"/>.
        /// </summary>
        public static void InitPostWindow()
        {
            AsyncManager.Init();

            DefaultContent.Init();
        }
예제 #34
0
        public NodeManager(MainService main)
        {
            Main = main;

            AsyncManager = new AsyncManager(Run);
        }
예제 #35
0
        public void TimeoutPropertyThrowsIfDurationIsOutOfRange()
        {
            // Arrange
            int timeout = -30;
            AsyncManager helper = new AsyncManager();

            // Act & assert
            Assert.ThrowsArgumentOutOfRange(
                delegate { helper.Timeout = timeout; }, "value",
                @"The timeout value must be non-negative or Timeout.Infinite.");
        }
예제 #36
0
 private void InitAsyncManager(DataLoadingEventArgs e)
 {
     m_asyncManager                 = new AsyncManager <object, DataLoadedEventArgs>(this.Name, new DataLoadWorker(this, e));
     m_asyncManager.WorkerDone     += new EventHandler <WorkerDoneEventArgs <DataLoadedEventArgs> >(LoadWork_WorkerDone);
     m_asyncManager.WorkerProgress += new EventHandler <WorkerProgressEventArgs <object> >(m_asyncManager_WorkerProgress);
 }
        void SearchWindow()
        {
            ImGui.Text(isSearchInfocards ? "Search Infocards" : "Search Strings");
            searchBuffer.InputText("##searchtext", ImGuiInputTextFlags.None, 200);
            ImGui.Checkbox("Case Sensitive", ref searchCaseSensitive);
            ImGui.Checkbox("Match Whole World", ref searchWholeWord);
            if (ImGui.Button("Go"))
            {
                var str = searchBuffer.GetText();
                if (!string.IsNullOrWhiteSpace(str))
                {
                    resultTitle = ImGuiExt.IDSafe($"Results for '{str}'");
                    dialogState = 1;
                    Regex r;
                    var   regOptions = searchCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
                    if (searchWholeWord)
                    {
                        r = new Regex($"\\b{Regex.Escape(str)}\\b", regOptions);
                    }
                    else
                    {
                        r = new Regex(Regex.Escape(str), regOptions);
                    }

                    if (isSearchInfocards)
                    {
                        AsyncManager.RunTask(() =>
                        {
                            var results    = new List <int>();
                            var resStrings = new List <string>();
                            foreach (var kv in manager.AllXml)
                            {
                                if (r.IsMatch(kv.Value))
                                {
                                    results.Add(kv.Key);
                                    resStrings.Add(kv.Value);
                                }
                            }
                            searchResults        = results.ToArray();
                            searchStrings        = resStrings.ToArray();
                            searchStringPreviews = new string[searchStrings.Length];
                            dialogState          = 2;
                        });
                    }
                    else
                    {
                        AsyncManager.RunTask(() =>
                        {
                            var results    = new List <int>();
                            var resStrings = new List <string>();
                            foreach (var kv in manager.AllStrings)
                            {
                                if (r.IsMatch(kv.Value))
                                {
                                    results.Add(kv.Key);
                                    resStrings.Add(kv.Value);
                                }
                            }
                            searchResults = results.ToArray();
                            searchStrings = resStrings.ToArray();
                            dialogState   = 2;
                        });
                    }
                }
            }
            ImGui.SameLine();
            if (ImGui.Button("Cancel"))
            {
                ImGui.CloseCurrentPopup();
            }
        }
예제 #38
0
        public void TimeoutPropertyThrowsIfDurationIsOutOfRange() {
            // Arrange
            int timeout = -30;
            AsyncManager helper = new AsyncManager();

            // Act & assert
            ExceptionHelper.ExpectArgumentOutOfRangeException(
                delegate {
                    helper.Timeout = timeout;
                }, "value",
                @"The timeout value must be non-negative or Timeout.Infinite.
Parameter name: value");
        }
예제 #39
0
 static AsyncCallback GetMvcCallbackInvocationActionFrom <T>(Action <T> callback, AsyncManager am)
 {
     return(asyncResult =>
     {
         HandleAsyncResult(callback, asyncResult);
         am.OutstandingOperations.Decrement();
     });
 }
        // Where we actually load the assetbundles from the local disk.
        static ITask <LoadedAssetBundle> LoadAssetBundleInternal(string assetBundleName, bool isManifest)
        {
            // Already loaded.
            var name = SeperatorRegex.Replace(assetBundleName, "/");
            ITask <LoadedAssetBundle> bundle;

            if (AssetBundles.TryGetValue(name, out bundle))
            {
                bundle.Then(b => b.ReferencedCount++);
                return(bundle);
            }

            ITask <string> pathTask;

            if (isManifest)
            {
                pathTask = Task.FromResult(BundleUtility.GetLocalBundlePath(name));
            }
            else
            {
                pathTask = Manifest.Then(manfiest => {
                    if (manfiest == null)
                    {
                        return(null);
                    }
                    foreach (var path in manfiest[name].Paths)
                    {
                        var fullPath = BundleUtility.GetLocalBundlePath(path);
                        if (File.Exists(fullPath))
                        {
                            return(fullPath);
                        }
                    }
                    throw new FileNotFoundException("No valid path for asset bundle {0} could be found.".With(name));
                });
            }
            // For manifest assetbundle, always download it as we don't have hash for it.
            var task = pathTask.Then(path => {
                var operation = AssetBundle.LoadFromFileAsync(path);
                return(AsyncManager.AddOperation(operation).Then(request => {
                    var assetBundle = request.assetBundle;
                    if (assetBundle == null)
                    {
                        throw new Exception("{0} is not a valid asset bundle.".With(name));
                    }
                    LoadedAssetBundle loadedBundle;
                    if (isManifest)
                    {
                        loadedBundle = new LoadedAssetBundle(
                            new BundleMetadata(assetBundleName,
                                               new Hash128(),
                                               Enumerable.Empty <BundleMetadata>(),
                                               Enumerable.Empty <string>()),
                            assetBundle);
                    }
                    else
                    {
                        loadedBundle = new LoadedAssetBundle(Manifest.Result[name], assetBundle);
                    }
                    log.Info("Loaded bundle \"{0}\" from {1}.", name, path);
                    return loadedBundle;
                }));
            });

            AssetBundles.Add(name, task);
            return(task);
        }
예제 #41
0
 public void FooAsync(int id1)
 {
     _func = o => Convert.ToString(o, CultureInfo.InvariantCulture) + id1.ToString(CultureInfo.InvariantCulture);
     AsyncManager.Parameters["id2"] = "Hello world: ";
     AsyncManager.Finish();
 }
예제 #42
0
 // The AsyncAwake function should be used instead of the awake function
 private void Awake()
 {
     // self-registering instance
     AsyncManager.Instance().addAsyncComponent(this);
     this.AsyncAwake();
 }
        public void RegisterTask_SynchronousCompletion() {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);
            bool endDelegateWasCalled = false;

            Func<AsyncCallback, IAsyncResult> beginDelegate = callback => {
                Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter was not incremented properly.");
                MockAsyncResult asyncResult = new MockAsyncResult(true /* completedSynchronously */);
                callback(asyncResult);
                return asyncResult;
            };
            Action<IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.IsFalse(syncContext.SendWasCalled, "Synchronous call to End() should not have been routed through SynchronizationContext.Send()");
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }