Ejemplo n.º 1
0
        public void ConnectToServer(string ip, int port = 0, bool passProtected = false, string myPass = "")
        {
            if (IsOnServer())
            {
                Client.Disconnect("Switching servers");
                Wait(1000);
            }
            ShowLoadingPrompt("Loading");
            Function.Call(Hash.DISPLAY_RADAR, false);

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            if (!_minimapSet)
            {
                var scal = new Scaleform("minimap");
                scal.CallFunction("MULTIPLAYER_IS_ACTIVE", true, false);

                Function.Call(Hash._SET_RADAR_BIGMAP_ENABLED, true, false);
                Function.Call(Hash._SET_RADAR_BIGMAP_ENABLED, false, false);

                _minimapSet = true;
            }

            Chat.Init();

            Client.Shutdown("Shutdown");
            Wait(1000);
            var cport = GetOpenUdpPort();

            if (cport == 0)
            {
                Util.Util.SafeNotify("No available UDP port was found.");
                return;
            }
            _config.Port = cport;
            Client       = new NetClient(_config);
            Client.Start();

            lock (Npcs) Npcs = new Dictionary <string, SyncPed>();
            lock (_tickNatives) _tickNatives = new Dictionary <string, NativeData>();

            var msg = Client.CreateMessage();

            var obj = new ConnectionRequest();

            obj.SocialClubName = string.IsNullOrWhiteSpace(Game.Player.Name) ? "Unknown" : Game.Player.Name; // To be used as identifiers in server files
            obj.DisplayName    = string.IsNullOrWhiteSpace(PlayerSettings.DisplayName) ? obj.SocialClubName : PlayerSettings.DisplayName.Trim();
            obj.ScriptVersion  = CurrentVersion.ToString();
            obj.CEF            = !CefUtil.DISABLE_CEF;
            obj.CEFDevtool     = EnableDevTool;
            obj.GameVersion    = (byte)Game.Version;
            obj.MediaStream    = EnableMediaStream;

            if (passProtected)
            {
                if (!string.IsNullOrWhiteSpace(myPass))
                {
                    obj.Password = myPass;
                }
                else
                {
                    MainMenu.TemporarilyHidden = true;
                    obj.Password = Game.GetUserInput();
                    MainMenu.TemporarilyHidden = false;
                }
            }

            var bin = SerializeBinary(obj);

            msg.Write((byte)PacketType.ConnectionRequest);
            msg.Write(bin.Length);
            msg.Write(bin);

            try
            {
                Client.Connect(ip, port == 0 ? Port : port, msg);
            }
            catch (NetException ex)
            {
                GTA.UI.Screen.ShowNotification("~b~~h~GTA Network~h~~w~~n~" + ex.Message);
                OnLocalDisconnect();
                return;
            }

            var pos = Game.Player.Character.Position;

            Function.Call(Hash.CLEAR_AREA_OF_PEDS, pos.X, pos.Y, pos.Z, 100f, 0);
            Function.Call(Hash.CLEAR_AREA_OF_VEHICLES, pos.X, pos.Y, pos.Z, 100f, 0);

            Function.Call(Hash.SET_GARBAGE_TRUCKS, 0);
            Function.Call(Hash.SET_RANDOM_BOATS, 0);
            Function.Call(Hash.SET_RANDOM_TRAINS, 0);

            Function.Call(Hash.CLEAR_ALL_BROKEN_GLASS);

            DisableSlowMo();

            Game.TimeScale = 1;

            ResetPlayer();

            _currentServerIp   = ip;
            _currentServerPort = port == 0 ? Port : port;
        }
Ejemplo n.º 2
0
        public async Task Await_MultipleAwaits_FirstCompletesAccordingToOptions_RestCompleteAsynchronously(
            int numContinuations, bool runContinuationsAsynchronously, bool valueTask, object scheduler)
        {
            await Task.Factory.StartNew(async delegate
            {
                if (scheduler is SynchronizationContext sc)
                {
                    SynchronizationContext.SetSynchronizationContext(sc);
                }

                var tcs = runContinuationsAsynchronously ? new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) : new TaskCompletionSource();

                var tl    = new ThreadLocal <int>();
                var tasks = new List <Task>();

                for (int i = 1; i <= numContinuations; i++)
                {
                    bool expectedSync = i == 1 && !runContinuationsAsynchronously;

                    tasks.Add(ThenAsync(tcs.Task, () =>
                    {
                        Assert.Equal(expectedSync ? 42 : 0, tl.Value);

                        switch (scheduler)
                        {
                        case null:
                            Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
                            Assert.Null(SynchronizationContext.Current);
                            break;

                        case TaskScheduler ts:
                            Assert.Same(ts, TaskScheduler.Current);
                            Assert.Null(SynchronizationContext.Current);
                            break;

                        case SynchronizationContext sc:
                            Assert.Same(sc, SynchronizationContext.Current);
                            Assert.Same(TaskScheduler.Default, TaskScheduler.Current);
                            break;
                        }
                    }));

                    async Task ThenAsync(Task task, Action action)
                    {
                        if (valueTask)
                        {
                            await new ValueTask(task);
                        }
                        else
                        {
                            await task;
                        }
                        action();
                    }
                }

                Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status));

                tl.Value = 42;
                tcs.SetResult();
                tl.Value = 0;

                SynchronizationContext.SetSynchronizationContext(null);
                await Task.WhenAll(tasks);
            }, CancellationToken.None, TaskCreationOptions.None, scheduler as TaskScheduler ?? TaskScheduler.Default).Unwrap();
Ejemplo n.º 3
0
        public static void Initialize(bool updateAddinRegistry)
        {
            if (initialized)
            {
                return;
            }

            Counters.RuntimeInitialization.BeginTiming();
            SetupInstrumentation();

            Platform.Initialize();

            // Set a default sync context
            if (SynchronizationContext.Current == null)
            {
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            }

            // Hook up the SSL certificate validation codepath
            ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
                if (sslPolicyErrors == SslPolicyErrors.None)
                {
                    return(true);
                }

                if (sender is WebRequest)
                {
                    sender = ((WebRequest)sender).RequestUri.Host;
                }
                return(WebCertificateService.GetIsCertificateTrusted(sender as string, certificate.GetPublicKeyString()));
            };

            AddinManager.AddinLoadError += OnLoadError;
            AddinManager.AddinLoaded    += OnLoad;
            AddinManager.AddinUnloaded  += OnUnload;

            try {
                Counters.RuntimeInitialization.Trace("Initializing Addin Manager");

                string configDir, addinsDir, databaseDir;
                GetAddinRegistryLocation(out configDir, out addinsDir, out databaseDir);
                AddinManager.Initialize(configDir, addinsDir, databaseDir);
                AddinManager.InitializeDefaultLocalizer(new DefaultAddinLocalizer());

                if (updateAddinRegistry)
                {
                    AddinManager.Registry.Update(null);
                }
                setupService = new AddinSetupService(AddinManager.Registry);
                Counters.RuntimeInitialization.Trace("Initialized Addin Manager");

                PropertyService.Initialize();

                WebRequestHelper.Initialize();
                Mono.Addins.Setup.WebRequestHelper.SetRequestHandler(WebRequestHelper.GetResponse);

                //have to do this after the addin service and property service have initialized
                if (UserDataMigrationService.HasSource)
                {
                    Counters.RuntimeInitialization.Trace("Migrating User Data from MD " + UserDataMigrationService.SourceVersion);
                    UserDataMigrationService.StartMigration();
                }

                RegisterAddinRepositories();

                Counters.RuntimeInitialization.Trace("Initializing Assembly Service");
                systemAssemblyService = new SystemAssemblyService();
                systemAssemblyService.Initialize();

                initialized = true;
            } catch (Exception ex) {
                Console.WriteLine(ex);
                AddinManager.AddinLoadError -= OnLoadError;
                AddinManager.AddinLoaded    -= OnLoad;
                AddinManager.AddinUnloaded  -= OnUnload;
            } finally {
                Counters.RuntimeInitialization.EndTiming();
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Stores the current synchronization context and sets the current
 /// context to be synchronous.
 /// </summary>
 /// <param name="methodUnderTest"></param>
 public override void Before(System.Reflection.MethodInfo methodUnderTest)
 {
     _originalContext = SynchronizationContext.Current;
     SynchronizationContext.SetSynchronizationContext(new SynchronousSynchronizationContext());
 }
Ejemplo n.º 5
0
 /// <summary>Shut down everything.</summary>
 /// <remarks>The pending callbacks are not dispatched, they are dropped silently.</remarks>
 public void Dispose()
 {
     SynchronizationContext.SetSynchronizationContext(null);
     s_current = null;
     synchronizationContext?.Dispose();
 }
Ejemplo n.º 6
0
 public void MyTestCleanup()
 {
     SynchronizationContext.SetSynchronizationContext(null);
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes the <see cref="TestState"/> for a new spec.
        /// </summary>
        /// <param name="system">The actor system this test will use. Can be null.</param>
        /// <param name="config">The configuration that <paramref name="system"/> will use if it's null.</param>
        /// <param name="actorSystemName">The name that <paramref name="system"/> will use if it's null.</param>
        /// <param name="testActorName">The name of the test actor. Can be null.</param>
        protected void InitializeTest(ActorSystem system, ActorSystemSetup config, string actorSystemName, string testActorName)
        {
            _testState = new TestState();

            if (system == null)
            {
                var bootstrap = config.Get <BootstrapSetup>();
                var configWithDefaultFallback = bootstrap.HasValue
                    ? bootstrap.Value.Config.Select(c => c == _defaultConfig ? c : c.WithFallback(_defaultConfig))
                    : _defaultConfig;

                var newBootstrap = BootstrapSetup.Create().WithConfig(
                    configWithDefaultFallback.HasValue
                        ? configWithDefaultFallback.Value
                        : _defaultConfig);
                if (bootstrap.FlatSelect(x => x.ActorRefProvider).HasValue)
                {
                    newBootstrap =
                        newBootstrap.WithActorRefProvider(bootstrap.FlatSelect(x => x.ActorRefProvider).Value);
                }
                system = ActorSystem.Create(actorSystemName ?? "test", config.WithSetup(newBootstrap));
            }

            _testState.System = system;

            system.RegisterExtension(new TestKitExtension());
            system.RegisterExtension(new TestKitAssertionsExtension(_assertions));

            _testState.TestKitSettings    = TestKitExtension.For(_testState.System);
            _testState.Queue              = new BlockingQueue <MessageEnvelope>();
            _testState.Log                = Logging.GetLogger(system, GetType());
            _testState.EventFilterFactory = new EventFilterFactory(this);

            //register the CallingThreadDispatcherConfigurator
            _testState.System.Dispatchers.RegisterConfigurator(CallingThreadDispatcher.Id,
                                                               new CallingThreadDispatcherConfigurator(_testState.System.Settings.Config, _testState.System.Dispatchers.Prerequisites));

            if (string.IsNullOrEmpty(testActorName))
            {
                testActorName = "testActor" + _testActorId.IncrementAndGet();
            }

            var testActor = CreateTestActor(system, testActorName);

            //Wait for the testactor to start
            // Calling sync version here, since .Wait() causes deadlock
            AwaitCondition(() =>
            {
                var repRef = testActor as IRepointableRef;
                return(repRef == null || repRef.IsStarted);
            }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10));

            if (!(this is INoImplicitSender))
            {
                InternalCurrentActorCellKeeper.Current = (ActorCell)((ActorRefWithCell)testActor).Underlying;
            }
            else if (!(this is TestProbe))
            //HACK: we need to clear the current context when running a No Implicit Sender test as sender from an async test may leak
            //but we should not clear the current context when creating a testprobe from a test
            {
                InternalCurrentActorCellKeeper.Current = null;
            }
            SynchronizationContext.SetSynchronizationContext(
                new ActorCellKeepingSynchronizationContext(InternalCurrentActorCellKeeper.Current));

            _testState.TestActor = testActor;
        }
        IEnumerable <OrchestratorAction> ExecuteCore(IEnumerable <HistoryEvent> eventHistory)
        {
            SynchronizationContext prevCtx = SynchronizationContext.Current;

            try
            {
                SynchronizationContext syncCtx = new TaskOrchestrationSynchronizationContext(this.decisionScheduler);
                SynchronizationContext.SetSynchronizationContext(syncCtx);
                OrchestrationContext.IsOrchestratorThread = true;

                try
                {
                    foreach (HistoryEvent historyEvent in eventHistory)
                    {
                        if (historyEvent.EventType == EventType.OrchestratorStarted)
                        {
                            var decisionStartedEvent = (OrchestratorStartedEvent)historyEvent;
                            this.context.CurrentUtcDateTime = decisionStartedEvent.Timestamp;
                            continue;
                        }

                        this.context.IsReplaying = historyEvent.IsPlayed;
                        ProcessEvent(historyEvent);
                        historyEvent.IsPlayed = true;
                    }

                    // check if workflow is completed after this replay
                    if (!this.context.HasOpenTasks)
                    {
                        if (this.result.IsCompleted)
                        {
                            if (this.result.IsFaulted)
                            {
                                Debug.Assert(this.result.Exception != null);

                                this.context.FailOrchestration(this.result.Exception.InnerExceptions.FirstOrDefault());
                            }
                            else
                            {
                                this.context.CompleteOrchestration(this.result.Result);
                            }
                        }

                        // TODO: It is an error if result is not completed when all OpenTasks are done.
                        // Throw an exception in that case.
                    }
                }
                catch (NonDeterministicOrchestrationException exception)
                {
                    this.context.FailOrchestration(exception);
                }

                return(this.context.OrchestratorActions);
            }
            finally
            {
                this.orchestrationRuntimeState.Status = this.taskOrchestration.GetStatus();
                SynchronizationContext.SetSynchronizationContext(prevCtx);
                OrchestrationContext.IsOrchestratorThread = false;
            }
        }
Ejemplo n.º 9
0
        private static void Main(string[] args)
        {
            // 异步方法全部会回掉到主线程
            OneThreadSynchronizationContext contex = new OneThreadSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(contex);

            try
            {
                /*string strConn = "Database=usersdata;Data Source=127.0.0.1;";
                 * strConn += "User Id=root;Password=066047;port=3306;";
                 * MySqlConnection sqlConn_ = new MySqlConnection(strConn);
                 * try
                 * {
                 *  sqlConn_.Open();
                 *  Console.WriteLine("[数据库]连接成功");
                 * }
                 * catch (Exception e)
                 * {
                 *  Console.WriteLine("[数据库]连接失败" + e.Message);
                 *  return;
                 * }*/

                Game.EventSystem.Add(DLLType.Model, typeof(Game).Assembly);
                Game.EventSystem.Add(DLLType.Hotfix, DllHelper.GetHotfixAssembly());

                Options     options     = Game.Scene.AddComponent <OptionComponent, string[]>(args).Options;
                StartConfig startConfig = Game.Scene.AddComponent <StartConfigComponent, string, int>(options.Config, options.AppId).StartConfig;

                if (!options.AppType.Is(startConfig.AppType))
                {
                    Log.Error("命令行参数apptype与配置不一致");
                    return;
                }

                IdGenerater.AppId = options.AppId;

                LogManager.Configuration.Variables["appType"]       = startConfig.AppType.ToString();
                LogManager.Configuration.Variables["appId"]         = startConfig.AppId.ToString();
                LogManager.Configuration.Variables["appTypeFormat"] = $"{startConfig.AppType,-8}";
                LogManager.Configuration.Variables["appIdFormat"]   = $"{startConfig.AppId:D3}";

                Log.Info($"server start........................ {startConfig.AppId} {startConfig.AppType}");

                Game.Scene.AddComponent <OpcodeTypeComponent>();
                Game.Scene.AddComponent <MessageDispatherComponent>();

                // 根据不同的AppType添加不同的组件
                OuterConfig  outerConfig  = startConfig.GetComponent <OuterConfig>();
                InnerConfig  innerConfig  = startConfig.GetComponent <InnerConfig>();
                ClientConfig clientConfig = startConfig.GetComponent <ClientConfig>();

                switch (startConfig.AppType)
                {
                case AppType.Manager:
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <NetOuterComponent, IPEndPoint>(outerConfig.IPEndPoint);
                    Game.Scene.AddComponent <AppManagerComponent>();
                    break;

                case AppType.Realm:
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <NetOuterComponent, IPEndPoint>(outerConfig.IPEndPoint);
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <RealmGateAddressComponent>();
                    break;

                case AppType.Gate:
                    Game.Scene.AddComponent <PlayerComponent>();
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <NetOuterComponent, IPEndPoint>(outerConfig.IPEndPoint);
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <ActorMessageSenderComponent>();
                    Game.Scene.AddComponent <GateSessionKeyComponent>();
                    break;

                case AppType.Location:
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <LocationComponent>();
                    break;

                case AppType.Map:
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <UnitComponent>();
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <ActorMessageSenderComponent>();
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <ServerFrameComponent>();
                    break;

                case AppType.AllServer:
                    Game.Scene.AddComponent <ActorMessageSenderComponent>();
                    Game.Scene.AddComponent <PlayerComponent>();
                    Game.Scene.AddComponent <UnitComponent>();
                    //Game.Scene.AddComponent<DBComponent>();
                    //Game.Scene.AddComponent<DBProxyComponent>();
                    //Game.Scene.AddComponent<DBCacheComponent>();
                    Game.Scene.AddComponent <MySqlComponent>();
                    Game.Scene.AddComponent <LocationComponent>();
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <NetOuterComponent, IPEndPoint>(outerConfig.IPEndPoint);
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <AppManagerComponent>();
                    Game.Scene.AddComponent <RealmGateAddressComponent>();
                    Game.Scene.AddComponent <GateSessionKeyComponent>();
                    Game.Scene.AddComponent <ConfigComponent>();
                    Game.Scene.AddComponent <ServerFrameComponent>();
                    // Game.Scene.AddComponent<HttpComponent>();
                    break;

                case AppType.Benchmark:
                    Game.Scene.AddComponent <NetOuterComponent>();
                    Game.Scene.AddComponent <BenchmarkComponent, IPEndPoint>(clientConfig.IPEndPoint);
                    break;

                default:
                    throw new Exception($"命令行参数没有设置正确的AppType: {startConfig.AppType}");
                }

                while (true)
                {
                    try
                    {
                        Thread.Sleep(1);
                        contex.Update();
                        Game.EventSystem.Update();
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
Ejemplo n.º 10
0
 private TestWorkspace CreateWorkspace(bool disablePartialSolutions = true)
 {
     SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
     return(new TestWorkspace(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, disablePartialSolutions: disablePartialSolutions));
 }
 public async Task AsyncMethod(SynchronizationContext context)
 {
     SynchronizationContext.SetSynchronizationContext(context);
     await Task.Delay(0);
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Runs the poller on the caller's thread. Only returns when <see cref="Stop"/> or <see cref="StopAsync"/> are called from another thread.
        /// </summary>
        public void Run()
        {
            CheckDisposed();
            if (IsRunning)
            {
                throw new InvalidOperationException("NetMQPoller is already running");
            }

#if NET35
            m_pollerThread = Thread.CurrentThread;
#else
            var oldSynchronisationContext = SynchronizationContext.Current;
            SynchronizationContext.SetSynchronizationContext(new NetMQSynchronizationContext(this));
            m_isSchedulerThread.Value = true;
#endif
            m_stopSignaler.Reset();

            m_switch.SwitchOn();
            try
            {
                // Recalculate all timers now
                foreach (var timer in m_timers)
                {
                    if (timer.Enable)
                    {
                        timer.When = Clock.NowMs() + timer.Interval;
                    }
                }

                // Run until stop is requested
                while (!m_stopSignaler.IsStopRequested)
                {
                    if (m_isPollSetDirty)
                    {
                        RebuildPollset();
                    }

                    var pollStart = Clock.NowMs();

                    // Set tickless to "infinity"
                    long tickless = pollStart + int.MaxValue;

                    // Find the When-value of the earliest timer..
                    foreach (var timer in m_timers)
                    {
                        // If it is enabled but no When is set yet,
                        if (timer.When == -1 && timer.Enable)
                        {
                            // Set this timer's When to now plus it's Interval.
                            timer.When = pollStart + timer.Interval;
                        }

                        // If it has a When and that is earlier than the earliest found thus far,
                        if (timer.When != -1 && tickless > timer.When)
                        {
                            // save that value.
                            tickless = timer.When;
                        }
                    }

                    // Compute a timeout value - how many milliseconds from now that the earliest-timer will expire.
                    var timeout = tickless - pollStart;

                    // Use zero to indicate it has already expired.
                    if (timeout < 0)
                    {
                        timeout = 0;
                    }

                    var isItemAvailable = false;

                    if (m_pollSet.Length != 0)
                    {
                        isItemAvailable = m_netMqSelector.Select(m_pollSet, m_pollSet.Length, timeout);
                    }
                    else if (timeout > 0)
                    {
                        //TODO: Do we really want to simply sleep and return, doing nothing during this interval?
                        //TODO: Should a large value be passed it will sleep for a month literally.
                        //      Solution should be different, but sleep is more natural here than in selector (timers are not selector concern).
                        Debug.Assert(timeout <= int.MaxValue);
                        Thread.Sleep((int)timeout);
                    }

                    // Get the expected end time in case we time out. This looks redundant but, unfortunately,
                    // it happens that Poll takes slightly less than the requested time and 'Clock.NowMs() >= timer.When'
                    // may not true, even if it is supposed to be. In other words, even when Poll times out, it happens
                    // that 'Clock.NowMs() < pollStart + timeout'
                    var expectedPollEnd = !isItemAvailable ? pollStart + timeout : -1L;

                    // that way we make sure we can continue the loop if new timers are added.
                    // timers cannot be removed
                    foreach (var timer in m_timers)
                    {
                        if ((Clock.NowMs() >= timer.When || expectedPollEnd >= timer.When) && timer.When != -1)
                        {
                            timer.InvokeElapsed(this);

                            if (timer.Enable)
                            {
                                timer.When = Clock.NowMs() + timer.Interval;
                            }
                        }
                    }

                    for (var i = 0; i < m_pollSet.Length; i++)
                    {
                        NetMQSelector.Item item = m_pollSet[i];

                        if (item.Socket != null)
                        {
                            NetMQSocket socket = m_pollact[i];

                            if (item.ResultEvent.HasError())
                            {
                                if (++socket.Errors > 1)
                                {
                                    Remove(socket);
                                    item.ResultEvent = PollEvents.None;
                                }
                            }
                            else
                            {
                                socket.Errors = 0;
                            }

                            if (item.ResultEvent != PollEvents.None)
                            {
                                socket.InvokeEvents(this, item.ResultEvent);
                            }
                        }
                        else if (item.ResultEvent.HasError() || item.ResultEvent.HasIn())
                        {
                            Action <Socket> action;
                            if (m_pollinSockets.TryGetValue(item.FileDescriptor, out action))
                            {
                                action(item.FileDescriptor);
                            }
                        }
                    }
                }
            }
            finally
            {
                try
                {
                    foreach (var socket in m_sockets.ToList())
                    {
                        Remove(socket);
                    }
                }
                finally
                {
#if NET35
                    m_pollerThread = null;
#else
                    m_isSchedulerThread.Value = false;
                    SynchronizationContext.SetSynchronizationContext(oldSynchronisationContext);
#endif
                    m_switch.SwitchOff();
                }
            }
        }
Ejemplo n.º 13
0
 public void TestInitialize()
 {
     _progress  = 0;
     _cancelled = false;
     SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
 }
Ejemplo n.º 14
0
        // Processes and invokes delegates.
        private void DelegateProcedure()
        {
            lock (lockObject)
            {
                // Signal the constructor that the thread is now running.
                Monitor.Pulse(lockObject);
            }

            // Set this DelegateQueue as the SynchronizationContext for this thread.
            SynchronizationContext.SetSynchronizationContext(this);

            // Placeholder for DelegateQueueAsyncResult objects.
            DelegateQueueAsyncResult result = null;

            // While the DelegateQueue has not been disposed.
            while (true)
            {
                // Critical section.
                lock (lockObject)
                {
                    // If the DelegateQueue has been disposed, break out of loop; we're done.
                    if (disposed)
                    {
                        break;
                    }

                    // If there are delegates waiting to be invoked.
                    if (delegateQueue.Count > 0)
                    {
                        result = delegateQueue.Dequeue();
                    }
                    // Else there are no delegates waiting to be invoked.
                    else
                    {
                        // Wait for next delegate.
                        Monitor.Wait(lockObject);

                        // If the DelegateQueue has been disposed, break out of loop; we're done.
                        if (disposed)
                        {
                            break;
                        }

                        Debug.Assert(delegateQueue.Count > 0);

                        result = delegateQueue.Dequeue();
                    }
                }

                Debug.Assert(result != null);

                // Invoke the delegate.
                result.Invoke();

                if (result.NotificationType == NotificationType.BeginInvokeCompleted)
                {
                    InvokeCompletedEventArgs e = new InvokeCompletedEventArgs(
                        result.Method,
                        result.GetArgs(),
                        result.ReturnValue,
                        result.Error);

                    OnInvokeCompleted(e);
                }
                else if (result.NotificationType == NotificationType.PostCompleted)
                {
                    object[] args = result.GetArgs();

                    Debug.Assert(args.Length == 1);
                    Debug.Assert(result.Method is SendOrPostCallback);

                    PostCompletedEventArgs e = new PostCompletedEventArgs(
                        (SendOrPostCallback)result.Method,
                        args[0],
                        result.Error);

                    OnPostCompleted(e);
                }
                else
                {
                    Debug.Assert(result.NotificationType == NotificationType.None);
                }
            }

            Debug.WriteLine(delegateThread.Name + " Finished");
        }
Ejemplo n.º 15
0
 public AsyncVoidInvocationRegion()
 {
     _previousContext = SynchronizationContext.Current;
     _currentContext  = new AsyncSynchronizationContext();
     SynchronizationContext.SetSynchronizationContext(_currentContext);
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Initializes the Terminal.Gui application
        /// </summary>
        static void Init(Func <Toplevel> topLevelFactory, ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null)
        {
            if (_initialized && driver == null)
            {
                return;
            }

            if (_initialized)
            {
                throw new InvalidOperationException("Init must be bracketed by Shutdown");
            }

            // Used only for start debugging on Unix.
            //#if DEBUG
            //			while (!System.Diagnostics.Debugger.IsAttached) {
            //				System.Threading.Thread.Sleep (100);
            //			}
            //			System.Diagnostics.Debugger.Break ();
            //#endif

            // Reset all class variables (Application is a singleton).
            ResetState();

            // This supports Unit Tests and the passing of a mock driver/loopdriver
            if (driver != null)
            {
                if (mainLoopDriver == null)
                {
                    throw new ArgumentNullException("mainLoopDriver cannot be null if driver is provided.");
                }
                Driver = driver;
                Driver.Init(TerminalResized);
                MainLoop = new MainLoop(mainLoopDriver);
                SynchronizationContext.SetSynchronizationContext(new MainLoopSyncContext(MainLoop));
            }

            if (Driver == null)
            {
                var p = Environment.OSVersion.Platform;
                if (UseSystemConsole)
                {
                    Driver         = new NetDriver();
                    mainLoopDriver = new NetMainLoop(Driver);
                }
                else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
                {
                    Driver         = new WindowsDriver();
                    mainLoopDriver = new WindowsMainLoop(Driver);
                }
                else
                {
                    mainLoopDriver = new UnixMainLoop();
                    Driver         = new CursesDriver();
                }
                Driver.Init(TerminalResized);
                MainLoop = new MainLoop(mainLoopDriver);
                SynchronizationContext.SetSynchronizationContext(new MainLoopSyncContext(MainLoop));
            }
            Top          = topLevelFactory();
            Current      = Top;
            _initialized = true;
        }
Ejemplo n.º 17
0
 public override void Dispose()
 {
     SynchronizationContext.SetSynchronizationContext(_previousContext);
 }
Ejemplo n.º 18
0
        public static void Run(Host host)
        {
            SynchronizationContext.SetSynchronizationContext(OneThreadSynchronizationContext.Instance);

            Loop(host);
        }
Ejemplo n.º 19
0
 public void Init()
 {
     SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
 }
Ejemplo n.º 20
0
        private static void Main(string[] args)
        {
            // 异步方法全部会回掉到主线程
            SynchronizationContext.SetSynchronizationContext(OneThreadSynchronizationContext.Instance);

            try
            {
                Game.EventSystem.Add(DLLType.Model, typeof(Game).Assembly);
                Game.EventSystem.Add(DLLType.Hotfix, DllHelper.GetHotfixAssembly());

                Options     options     = Game.Scene.AddComponent <OptionComponent, string[]>(args).Options;
                StartConfig startConfig = Game.Scene.AddComponent <StartConfigComponent, string, int>(options.Config, options.AppId).StartConfig;

                if (!options.AppType.Is(startConfig.AppType))
                {
                    Log.Error("命令行参数apptype与配置不一致");
                    return;
                }

                IdGenerater.AppId = options.AppId;

                LogManager.Configuration.Variables["appType"]       = startConfig.AppType.ToString();
                LogManager.Configuration.Variables["appId"]         = startConfig.AppId.ToString();
                LogManager.Configuration.Variables["appTypeFormat"] = $"{startConfig.AppType,-8}";
                LogManager.Configuration.Variables["appIdFormat"]   = $"{startConfig.AppId:D3}";

                Log.Info($"server start........................ {startConfig.AppId} {startConfig.AppType}");

                Game.Scene.AddComponent <OpcodeTypeComponent>();
                Game.Scene.AddComponent <MessageDispatherComponent>();

                // 根据不同的AppType添加不同的组件
                OuterConfig  outerConfig  = startConfig.GetComponent <OuterConfig>();
                InnerConfig  innerConfig  = startConfig.GetComponent <InnerConfig>();
                ClientConfig clientConfig = startConfig.GetComponent <ClientConfig>();

                switch (startConfig.AppType)
                {
                case AppType.Manager:
                    Game.Scene.AddComponent <AppManagerComponent>();
                    Game.Scene.AddComponent <NetInnerComponent, string>(innerConfig.Address);
                    Game.Scene.AddComponent <NetOuterComponent, string>(outerConfig.Address);
                    break;

                case AppType.Realm:
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <NetInnerComponent, string>(innerConfig.Address);
                    Game.Scene.AddComponent <NetOuterComponent, string>(outerConfig.Address);
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <RealmGateAddressComponent>();
                    break;

                case AppType.Gate:
                    Game.Scene.AddComponent <PlayerComponent>();
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <NetInnerComponent, string>(innerConfig.Address);
                    Game.Scene.AddComponent <NetOuterComponent, string>(outerConfig.Address);
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <ActorMessageSenderComponent>();
                    Game.Scene.AddComponent <ActorLocationSenderComponent>();
                    Game.Scene.AddComponent <GateSessionKeyComponent>();
                    break;

                case AppType.Location:
                    Game.Scene.AddComponent <NetInnerComponent, string>(innerConfig.Address);
                    Game.Scene.AddComponent <LocationComponent>();
                    break;

                case AppType.Map:
                    Game.Scene.AddComponent <NetInnerComponent, string>(innerConfig.Address);
                    Game.Scene.AddComponent <UnitComponent>();
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <ActorMessageSenderComponent>();
                    Game.Scene.AddComponent <ActorLocationSenderComponent>();
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <PathfindingComponent>();
                    break;

                case AppType.AllServer:
                    Game.Scene.AddComponent <ActorMessageSenderComponent>();
                    Game.Scene.AddComponent <ActorLocationSenderComponent>();
                    Game.Scene.AddComponent <PlayerComponent>();
                    Game.Scene.AddComponent <UnitComponent>();
                    //PS:如果启动闪退有可能是服务器配置文件没有填数据库配置,请正确填写
                    //这里需要将DBComponent的Awake注释去掉才能连接MongoDB
                    Game.Scene.AddComponent <DBComponent>();
                    //这里需要加上DBCacheComponent才能操作MongoDB
                    Game.Scene.AddComponent <DBCacheComponent>();
                    Game.Scene.AddComponent <DBProxyComponent>();
                    Game.Scene.AddComponent <LocationComponent>();
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <NetInnerComponent, string>(innerConfig.Address);
                    Game.Scene.AddComponent <NetOuterComponent, string>(outerConfig.Address);
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <AppManagerComponent>();
                    Game.Scene.AddComponent <RealmGateAddressComponent>();
                    Game.Scene.AddComponent <GateSessionKeyComponent>();
                    Game.Scene.AddComponent <ConfigComponent>();
                    //Game.Scene.AddComponent<ServerFrameComponent>();
                    Game.Scene.AddComponent <PathfindingComponent>();
                    // Game.Scene.AddComponent<HttpComponent>();

                    //以下是斗地主服务端自定义全局组件

                    //GateGlobalComponent
                    Game.Scene.AddComponent <UserComponent>();
                    Game.Scene.AddComponent <LandlordsGateSessionKeyComponent>();

                    //MapGlobalComponent
                    Game.Scene.AddComponent <RoomComponent>();

                    //MatchGlobalComponent
                    Game.Scene.AddComponent <AllotMapComponent>();
                    Game.Scene.AddComponent <MatchComponent>();
                    Game.Scene.AddComponent <MatcherComponent>();
                    Game.Scene.AddComponent <MatchRoomComponent>();

                    //RealmGlobalComponent
                    Game.Scene.AddComponent <OnlineComponent>();
                    break;

                case AppType.Benchmark:
                    Game.Scene.AddComponent <NetOuterComponent>();
                    Game.Scene.AddComponent <BenchmarkComponent, string>(clientConfig.Address);
                    break;

                case AppType.BenchmarkWebsocketServer:
                    Game.Scene.AddComponent <NetOuterComponent, string>(outerConfig.Address);
                    break;

                case AppType.BenchmarkWebsocketClient:
                    Game.Scene.AddComponent <NetOuterComponent>();
                    Game.Scene.AddComponent <WebSocketBenchmarkComponent, string>(clientConfig.Address);
                    break;

                default:
                    throw new Exception($"命令行参数没有设置正确的AppType: {startConfig.AppType}");
                }

                while (true)
                {
                    try
                    {
                        Thread.Sleep(1);
                        OneThreadSynchronizationContext.Instance.Update();
                        Game.EventSystem.Update();
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            if (args.Length <= 0)
            {
                Log.Fatal("请输入服务器编号");
                return;
            }
            // 异步方法全部会回掉到主线程
            SynchronizationContext.SetSynchronizationContext(OneThreadSynchronizationContext.Instance);
            try
            {
                int    AppId      = Convert.ToInt32(args[0]);
                string configFile = "../../Config/StartConfig/LocalAllServer.json";
                if (args.Length >= 2)
                {
                    configFile = args[1];
                }
                Game.EventSystem.Add(DLLType.Model, typeof(Game).Assembly);
                //Game.EventSystem.Add(DLLType.Hotfix, DllHelper.GetHotfixAssembly());
                Game.EventSystem.Add(DLLType.Hotfix, typeof(Hotfix).Assembly);
                StartConfig startConfig = Game.Scene.AddComponent <StartConfigComponent, string, int>(configFile, AppId).StartConfig;
                IdGenerater.AppId = AppId;

                if (startConfig.AppType != AppType.Gate)
                {
                    Log.Error("命令行参数apptype与配置不一致");
                    return;
                }



                LogManager.Configuration.Variables["appType"]       = startConfig.AppType.ToString();
                LogManager.Configuration.Variables["appId"]         = startConfig.AppId.ToString();
                LogManager.Configuration.Variables["appTypeFormat"] = $"{startConfig.AppType,-8}";
                LogManager.Configuration.Variables["appIdFormat"]   = $"{startConfig.AppId:D3}";

                Log.Info($"server start........................ {startConfig.AppId} {startConfig.AppType}");

                Game.Scene.AddComponent <OpcodeTypeComponent>();
                Game.Scene.AddComponent <MessageDispatherComponent>();

                InnerConfig innerConfig = startConfig.GetComponent <InnerConfig>();
                OuterConfig outerConfig = startConfig.GetComponent <OuterConfig>();
                DBConfig    dbConfig    = startConfig.GetComponent <DBConfig>();


                Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                Game.Scene.AddComponent <NetOuterComponent, IPEndPoint>(outerConfig.IPEndPoint);
                Game.Scene.AddComponent <LocationProxyComponent>();
                Game.Scene.AddComponent <ActorMessageSenderComponent>();
                //Game.Scene.AddComponent<GateSessionKeyComponent>();
                Game.Scene.AddComponent <PlayerManagerComponent>();



                while (true)
                {
                    try
                    {
                        Thread.Sleep(1);
                        OneThreadSynchronizationContext.Instance.Update();
                        Game.EventSystem.Update();
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Log.Error(e);
            }
        }
Ejemplo n.º 22
0
        int Run(MonoDevelopOptions options)
        {
            CompositionManager.ConfigureUninitializedMefHandling(throwException: true);

            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Build Information{0}{1}", Environment.NewLine, SystemInformation.GetBuildInformation());
            LoggingService.LogInfo("Running on {0}", RuntimeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();
            IdeStartupTracker.StartupTracker.MarkSection("PlatformInitialization");

            GettextCatalog.Initialize();
            IdeStartupTracker.StartupTracker.MarkSection("GettextInitialization");

            LoggingService.LogInfo("Operating System: {0}", SystemInformation.GetOperatingSystemDescription());

            // The assembly resolver for MSBuild 15 assemblies needs to be defined early on.
            // Whilst Runtime.Initialize loads the MSBuild 15 assemblies from Mono this seems
            // to be too late to prevent the MEF composition and the static registrar from
            // failing to load the MonoDevelop.Ide assembly which now uses MSBuild 15 assemblies.
            ResolveMSBuildAssemblies();

            Counters.InitializationTracker = Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.InitializationTracker.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            // explicit GLib type system initialization for GLib < 2.36 before any other type system access
            GLib.GType.Init();

            var args = options.RemainingArgs.ToArray();

            IdeTheme.InitializeGtk(BrandingService.ApplicationName, ref args);

            startupInfo = new StartupInfo(options, args);
            if (startupInfo.HasFiles)
            {
                // If files are present, consider started from the commandline as being the same as file manager.
                // On macOS, we need to wait until the DidFinishLaunching notification to find out we were launched from the Finder
                IdeApp.LaunchReason = IdeApp.LaunchType.LaunchedFromFileManager;
            }
            else if (!Platform.IsMac)
            {
                IdeApp.LaunchReason = IdeApp.LaunchType.Normal;
            }

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            try {
                IdeApp.Customizer.Initialize(startupInfo);
            } catch (UnauthorizedAccessException ua) {
                LoggingService.LogError("Unauthorized access: " + ua.Message);
                return(1);
            }

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            IdeStartupTracker.StartupTracker.MarkSection("GtkInitialization");
            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Runtime.LoadAssemblyFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();
            IdeTheme.SetupXwtTheme();

            IdeStartupTracker.StartupTracker.MarkSection("XwtInitialization");

            //default to Windows IME on Windows
            if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(DispatchService.SynchronizationContext);
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            IdeStartupTracker.StartupTracker.MarkSection("DispatchInitialization");

            // Initialize Roslyn's synchronization context
            RoslynServices.RoslynService.Initialize();

            IdeStartupTracker.StartupTracker.MarkSection("RoslynInitialization");

            AddinManager.AddinLoadError += OnAddinError;

            Counters.InitializationTracker.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            // Register services used by the IDE

            RegisterServices();

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            instanceConnection = new IdeInstanceConnection(options.IpcTcp);

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles && instanceConnection.TryConnect(startupInfo))
            {
                return(0);
            }

            IdeStartupTracker.StartupTracker.MarkSection("RuntimeInitialization");

            bool restartRequested = PropertyService.Get("MonoDevelop.Core.RestartRequested", false);

            startupInfo.Restarted = restartRequested;
            PropertyService.Set("MonoDevelop.Core.RestartRequested", false);

            Counters.InitializationTracker.Trace("Initializing theme");

            IdeTheme.SetupGtkTheme();

            IdeApp.Customizer.OnCoreInitialized();

            IdeStartupTracker.StartupTracker.MarkSection("ThemeInitialized");

            IdeApp.IsRunning = true;

            Xwt.Application.TranslationCatalog = new XwtTranslationCatalog();

            // Load the main menu before running the main loop
            var commandService = Runtime.GetService <CommandManager> ().Result;
            var desktopService = Runtime.GetService <DesktopService> ().Result;

            desktopService.SetGlobalMenu(commandService, DefaultWorkbench.MainMenuPath, DefaultWorkbench.AppMenuPath);

            // Run the main loop
            Gtk.Application.Invoke((s, e) => {
                MainLoop(options, startupInfo).Ignore();
            });
            Gtk.Application.Run();

            IdeApp.IsRunning = false;

            IdeApp.Customizer.OnIdeShutdown();

            instanceConnection.Dispose();

            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();

            MonoDevelop.Components.GtkWorkarounds.Terminate();

            return(0);
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Restores the original synchronization context.
 /// </summary>
 /// <param name="methodUnderTest"></param>
 public override void After(System.Reflection.MethodInfo methodUnderTest)
 {
     SynchronizationContext.SetSynchronizationContext(_originalContext);
 }
Ejemplo n.º 24
0
 public void Dispose()
 {
     _disposables.ForEach(d => d.Dispose());
     SynchronizationContext.SetSynchronizationContext(_originalContext);
 }
Ejemplo n.º 25
0
        public static void OnCompleted_CompletesInAnotherSynchronizationContext(bool generic, bool?continueOnCapturedContext)
        {
            SynchronizationContext origCtx = SynchronizationContext.Current;

            try
            {
                // Create a context that tracks operations, and set it as current
                var validateCtx = new ValidateCorrectContextSynchronizationContext();
                Assert.Equal(0, validateCtx.PostCount);
                SynchronizationContext.SetSynchronizationContext(validateCtx);

                // Create a not-completed task and get an awaiter for it
                var mres = new ManualResetEventSlim();
                var tcs  = new TaskCompletionSource <object>();

                // Hook up a callback
                bool   postedInContext = false;
                Action callback        = () =>
                {
                    postedInContext = ValidateCorrectContextSynchronizationContext.t_isPostedInContext;
                    mres.Set();
                };
                if (generic)
                {
                    if (continueOnCapturedContext.HasValue)
                    {
                        tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                    }
                    else
                    {
                        tcs.Task.GetAwaiter().OnCompleted(callback);
                    }
                }
                else
                {
                    if (continueOnCapturedContext.HasValue)
                    {
                        ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                    }
                    else
                    {
                        ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
                    }
                }
                Assert.False(mres.IsSet, "Callback should not yet have run.");

                // Complete the task in another context and wait for the callback to run
                Task.Run(() => tcs.SetResult(null));
                mres.Wait();

                // Validate the callback ran and in the correct context
                bool shouldHavePosted = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
                Assert.Equal(shouldHavePosted ? 1 : 0, validateCtx.PostCount);
                Assert.Equal(shouldHavePosted, postedInContext);
            }
            finally
            {
                // Reset back to the original context
                SynchronizationContext.SetSynchronizationContext(origCtx);
            }
        }
Ejemplo n.º 26
0
 public DisposableAnalyserCodeFixVerifierSpec()
 {
     SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
 }
Ejemplo n.º 27
0
        public static void OnCompleted_CompletesInAnotherTaskScheduler(bool generic, bool?continueOnCapturedContext)
        {
            SynchronizationContext origCtx = SynchronizationContext.Current;

            try
            {
                SynchronizationContext.SetSynchronizationContext(null); // get off xunit's SynchronizationContext to avoid interactions with await

                var quwi = new QUWITaskScheduler();
                RunWithSchedulerAsCurrent(quwi, delegate
                {
                    Assert.True(TaskScheduler.Current == quwi, "Expected to be on target scheduler");

                    // Create the not completed task and get its awaiter
                    var mres = new ManualResetEventSlim();
                    var tcs  = new TaskCompletionSource <object>();

                    // Hook up the callback
                    bool ranOnScheduler = false;
                    Action callback     = () =>
                    {
                        ranOnScheduler = (TaskScheduler.Current == quwi);
                        mres.Set();
                    };
                    if (generic)
                    {
                        if (continueOnCapturedContext.HasValue)
                        {
                            tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                        }
                        else
                        {
                            tcs.Task.GetAwaiter().OnCompleted(callback);
                        }
                    }
                    else
                    {
                        if (continueOnCapturedContext.HasValue)
                        {
                            ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
                        }
                        else
                        {
                            ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
                        }
                    }
                    Assert.False(mres.IsSet, "Callback should not yet have run.");

                    // Complete the task in another scheduler and wait for the callback to run
                    Task.Run(delegate { tcs.SetResult(null); });
                    mres.Wait();

                    // Validate the callback ran on the right scheduler
                    bool shouldHaveRunOnScheduler = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
                    Assert.Equal(shouldHaveRunOnScheduler, ranOnScheduler);
                });
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(origCtx);
            }
        }
Ejemplo n.º 28
0
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Running on {0}", IdeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            IdeApp.Customizer.Initialize();

            Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            SetupTheme();

            var args = options.RemainingArgs.ToArray();

            Gtk.Application.Init(BrandingService.ApplicationName, ref args);

            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Assembly.LoadFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();

            //default to Windows IME on Windows
            if (Platform.IsWindows && Mono.TextEditor.GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = Mono.TextEditor.GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    Mono.TextEditor.GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            InternalLog.Initialize();
            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(new GtkSynchronizationContext());
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
//				foreach (var file in startupInfo.RequestedFileList) {
//					if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile (file.FileName)) {
//						options.NewWindow = true;
//						break;
//					}
//				}
            }

            Counters.Initialization.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            IdeApp.Customizer.OnCoreInitialized();

            Counters.Initialization.Trace("Initializing theme");

            DefaultTheme = Gtk.Settings.Default.ThemeName;
            string theme = IdeApp.Preferences.UserInterfaceTheme;

            if (string.IsNullOrEmpty(theme))
            {
                theme = DefaultTheme;
            }
            ValidateGtkTheme(ref theme);
            if (theme != DefaultTheme)
            {
                Gtk.Settings.Default.ThemeName = theme;
            }

            IProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }

                    if (options.IpcTcp)
                    {
                        try {
                            listen_socket.Close();
                            listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                        } catch (Exception exc) {
                            LoggingService.LogError("Error resetting TCP socket", exc);
                        }
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");
            string version = Assembly.GetEntryAssembly().GetName().Version.Major + "." + Assembly.GetEntryAssembly().GetName().Version.Minor;

            if (Assembly.GetEntryAssembly().GetName().Version.Build != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Build;
            }
            if (Assembly.GetEntryAssembly().GetName().Version.Revision != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Revision;
            }

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();

                if (errorsList.Count > 0)
                {
                    AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false);
                    if (!dlg.Run())
                    {
                        return(1);
                    }
                    reportedFailures = errorsList.Count;
                }

                if (!CheckSCPlugin())
                {
                    return(1);
                }

                // no alternative for Application.ThreadException?
                // Application.ThreadException += new ThreadExceptionEventHandler(ShowErrorBox);

                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                // Load requested files
                Counters.Initialization.Trace("Opening Files");

                // load previous combine
                if (IdeApp.Preferences.LoadPrevSolutionOnStartup && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    var proj = DesktopService.RecentFiles.GetProjects().FirstOrDefault();
                    if (proj != null)
                    {
                        IdeApp.Workspace.OpenWorkspaceItem(proj.FileName).WaitForCompleted();
                    }
                }

                IdeApp.OpenFiles(startupInfo.RequestedFileList);

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop failed to start"));
                MessageService.ShowFatalError(message, null, error);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true);
                dlg.Run();
            }

            errorsList = null;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow = IdeApp.Workbench.RootWindow;
            Thread.CurrentThread.Name = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();
            IdeApp.Run();

            IdeApp.Customizer.OnIdeShutdown();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }
            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();
            AddinManager.AddinLoadError -= OnAddinError;

            return(0);
        }
Ejemplo n.º 29
0
 public void Dispose()
 => SynchronizationContext.SetSynchronizationContext(_synchronizationContext);
Ejemplo n.º 30
0
 static void SetSynchronizationContext(SynchronizationContext context)
 {
     SynchronizationContext.SetSynchronizationContext(context);
 }