public override void Shutdown() { // shut down the dedicated threadpool and null it out Volatile.Write(ref _shuttingDown, 1); _dedicatedThreadPool?.Dispose(); _dedicatedThreadPool = null; }
public override IAccessableResource Construct() { var settings = new DedicatedThreadPoolSettings(numberOfThreads, $"{nameof(WhatNow)}.{nameof(ThreadPoolResourceDefinition)}.{Name}"); var pool = new DedicatedThreadPool(settings); return(new ThreadPool(pool, taskCreationOptions)); }
public async Task TestPlugins() { StringBuilder result = new StringBuilder(); IDictionary <string, ISchedulerPlugin> data = new Dictionary <string, ISchedulerPlugin>(); data["TestPlugin"] = new TestPlugin(result); IThreadPool threadPool = new DedicatedThreadPool { ThreadCount = 1 }; threadPool.Initialize(); DirectSchedulerFactory.Instance.CreateScheduler( "MyScheduler", "Instance1", threadPool, new RAMJobStore(), data, TimeSpan.Zero); IScheduler scheduler = await DirectSchedulerFactory.Instance.GetScheduler("MyScheduler"); await scheduler.Start(); await scheduler.Shutdown(); Assert.AreEqual("TestPlugin|MyScheduler|Start|Shutdown", result.ToString()); }
public void World_should_not_end_if_exception_thrown_in_user_callback() { var numThreads = 3; var threadIds = new ConcurrentBag <int>(); Action badCallback = () => { threadIds.Add(Thread.CurrentThread.ManagedThreadId); throw new Exception("DEATH TO THIS THREAD I SAY!"); }; Action goodCallback = () => { Thread.Sleep(20); threadIds.Add(Thread.CurrentThread.ManagedThreadId); }; using (var threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(numThreads))) { for (var i = 0; i < numThreads; i++) { threadPool.EnqueueWorkItem(badCallback); } //wait a second for all work to be completed Task.Delay(TimeSpan.FromSeconds(0.5)).Wait(); //run the job again. Should get 3 more managed thread IDs for (var i = 0; i < numThreads; i++) { threadPool.EnqueueWorkItem(goodCallback); } Task.Delay(TimeSpan.FromSeconds(0.5)).Wait(); } // half of thread IDs should belong to failed threads, other half to successful ones Assert.AreEqual(numThreads * 2, threadIds.Distinct().Count()); }
public void Should_release_threads_when_idle() { var numThreads = 3; var threadIds = new ConcurrentBag <int>(); Action callback = () => { Thread.Sleep(15); //sleep, so another thread is forced to take the work threadIds.Add(Thread.CurrentThread.ManagedThreadId); }; using (var threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(numThreads))) { for (var i = 0; i < numThreads; i++) { threadPool.EnqueueWorkItem(callback); } //wait a second for all work to be completed Task.Delay(TimeSpan.FromSeconds(0.5)).Wait(); //run the job again. Should get 3 more managed thread IDs for (var i = 0; i < numThreads; i++) { threadPool.EnqueueWorkItem(callback); } Task.Delay(TimeSpan.FromSeconds(0.5)).Wait(); } Assert.AreEqual(numThreads * 2, threadIds.Distinct().Count()); }
public MiNetServer() { ServerRole = Config.GetProperty("ServerRole", ServerRole.Full); InacvitityTimeout = Config.GetProperty("InactivityTimeout", 8500); ResendThreshold = Config.GetProperty("ResendThreshold", 10); int confMinWorkerThreads = Config.GetProperty("MinWorkerThreads", -1); int confMinCompletionPortThreads = Config.GetProperty("MinCompletionPortThreads", -1); int threads; int iothreads; ThreadPool.GetMinThreads(out threads, out iothreads); //if (confMinWorkerThreads != -1) threads = confMinWorkerThreads; //else threads *= 4; //if (confMinCompletionPortThreads != -1) iothreads = confMinCompletionPortThreads; //else iothreads *= 4; //ThreadPool.SetMinThreads(threads, iothreads); FastThreadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(Environment.ProcessorCount)); LevelThreadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(Environment.ProcessorCount)); _receiveThreadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(Environment.ProcessorCount)); }
public ChunkProcessor(DedicatedThreadPool threadPool, bool useAlexChunks, CancellationToken cancellationToken) { Instance = this; ThreadPool = threadPool; UseAlexChunks = useAlexChunks; CancellationToken = cancellationToken; Queue = new ConcurrentQueue <Action>(); }
public DedicatedThreadPoolFiber(IExecutor executor, int numThreads) { Executor = executor ?? new BasicExecutor(); numThreads.NotNegative(); numThreads.NotLessThan(1); _numThreads = numThreads; _threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(numThreads)); Running = true; }
private static void Main(string[] args) { try { AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; Console.WriteLine("Press <Enter> to start emulation..."); Console.ReadLine(); //int threads; //int iothreads; //ThreadPool.GetMaxThreads(out threads, out iothreads); //ThreadPool.SetMaxThreads(threads, 4000); //ThreadPool.GetMinThreads(out threads, out iothreads); //ThreadPool.SetMinThreads(4000, 4000); DedicatedThreadPool threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(Environment.ProcessorCount)); Emulator emulator = new Emulator { Running = true }; Stopwatch watch = new Stopwatch(); watch.Start(); long start = DateTime.UtcNow.Ticks; IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 19132); for (int j = 0; j < NumberOfBots; j++) { string playerName = $"TheGrey{j + 1:D3}"; ClientEmulator client = new ClientEmulator(threadPool, emulator, DurationOfConnection, playerName, (int)(DateTime.UtcNow.Ticks - start), endPoint, RanSleepMin, RanSleepMax, RequestChunkRadius); new Thread(o => { client.EmulateClient(); }) { IsBackground = true }.Start(); Thread.Sleep(TimeBetweenSpawns); } Console.WriteLine("Press <enter> to stop all clients."); Console.ReadLine(); emulator.Running = false; } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Emulation complete. Press <enter> to exit."); Console.ReadLine(); }
public TaskList(TaskFactory taskFactory) { pool = null; scheduler = null; this.taskFactory = taskFactory; cancellationTokenSource = new CancellationTokenSource(); tasks = new List <Task>(); }
public TaskList(int maxDegreeOfParallelism) { pool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(maxDegreeOfParallelism)); scheduler = new DedicatedThreadPoolTaskScheduler(pool); taskFactory = new TaskFactory(scheduler); cancellationTokenSource = new CancellationTokenSource(); tasks = new List <Task>(); }
public ThreadPool(DedicatedThreadPool threadPool, TaskCreationOptions taskCreationOptions) { this.threadPool = threadPool; cancellationTokenSource = new CancellationTokenSource(); taskScheduler = new DedicatedThreadPoolTaskScheduler(threadPool); taskFactory = new TaskFactory( cancellationTokenSource.Token , taskCreationOptions , TaskContinuationOptions.None , taskScheduler); }
/// <summary> /// Creates a new thread pool. /// </summary> /// <param name="name">A name of this thread pool.</param> /// <param name="threadsNumber">A number of thread in this thread pool. Default value is a count of processors.</param> /// <param name="threadsPriority">A priority of threads in this thread pool. Default value is </param> public FixedThreadPool( string name = null, int?threadsNumber = null, ThreadPriority?threadsPriority = null) { var settings = new DedicatedThreadPoolSettings( threadsNumber ?? Environment.ProcessorCount, threadsPriority, string.IsNullOrWhiteSpace(name) ? "HeliosThreadPool-" + Guid.NewGuid() : name); _threadPool = new DedicatedThreadPool(settings); }
public ClientEmulator(DedicatedThreadPool threadPool, Emulator emulator, TimeSpan timeToRun, string name, int clientId, IPEndPoint endPoint, int ranMin = 150, int ranMax = 450, int chunkRadius = 8) { _threadPool = threadPool; Emulator = emulator; TimeToRun = timeToRun; Name = name; ClientId = clientId; EndPoint = endPoint; RanMin = ranMin; RanMax = ranMax; ChunkRadius = chunkRadius; }
public void Should_process_multithreaded_workload() { var atomicCounter = new AtomicCounter(0); using (var threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(2))) { for (var i = 0; i < 1000; i++) { threadPool.QueueUserWorkItem(() => atomicCounter.GetAndIncrement()); } SpinWait.SpinUntil(() => atomicCounter.Current == 1000, TimeSpan.FromSeconds(1)); } Assert.Pass(string.Format("Passed! Final counter value: {0} / Expected {1}", atomicCounter.Current, 1000)); }
public ActionDispatcher(IEnumerable <IActionPipe> actionPipes, int numberOfThreadPoolThreads = 8) { pipes = actionPipes.ToArray(); resourceManager = new ResourceManager(); cancellationTokenSource = new CancellationTokenSource(); tasks = new Dictionary <IActionPipe, Task>(pipes.Length); pool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(numberOfThreadPoolThreads)); Scheduler = new DedicatedThreadPoolTaskScheduler(pool); TaskFactory = new TaskFactory(cancellationTokenSource.Token, TaskCreationOptions.None, TaskContinuationOptions.None, Scheduler); SetUpProcessingDefaultEvents(); state = DispatcherState.NotStarted; }
public NetConnection(Direction direction, Socket socket, ConnectionConfirmed confirmdAction = null, DedicatedThreadPool threadPool = null) { Direction = direction; Socket = socket; RemoteEndPoint = Socket.RemoteEndPoint; ThreadPool = threadPool; ConnectionConfirmed = confirmdAction; CancellationToken = new CancellationTokenSource(); ConnectionState = ConnectionState.Handshake; IsConnected = true; PacketWriteQueue = new BlockingCollection <EnqueuedPacket>(); HandlePacketQueue = new BlockingCollection <TemporaryPacketData>(); }
public Sender() { _sendPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(1, ThreadType.Background, "Send-Pool")); _sendPool.QueueUserWorkItem(() => { // Initialize Static Core _deviceContext = DeviceContext.Create(); _glContext = _deviceContext.CreateContext(IntPtr.Zero); _deviceContext.MakeCurrent(_glContext); //_senderLocker = new object(); // Initialize Core _sender = new SpoutSender(); _sender.CreateSender(SenderName, _width, _height, 0); }); }
public BedrockClient(Alex alex, IPEndPoint endpoint, PlayerProfile playerProfile, DedicatedThreadPool threadPool, BedrockWorldProvider wp) : base(endpoint, playerProfile.Username, threadPool) { PlayerProfile = playerProfile; CancellationTokenSource = new CancellationTokenSource(); Alex = alex; WorldProvider = wp; ConnectionAcceptedWaitHandle = new ManualResetEventSlim(false); MessageDispatcher = new McpeClientMessageDispatcher(new BedrockClientPacketHandler(this, alex, CancellationTokenSource.Token)); CurrentLocation = new MiNET.Utils.PlayerLocation(0, 0, 0); OptionsProvider = alex.Services.GetService <IOptionsProvider>(); XblmsaService = alex.Services.GetService <XBLMSAService>(); base.ChunkRadius = Options.VideoOptions.RenderDistance; Options.VideoOptions.RenderDistance.Bind(RenderDistanceChanged); _threadPool = threadPool; }
public void ConnectToServer(IPEndPoint serverEndPoint, PlayerProfile profile, bool bedrock = false, string hostname = null) { var oldNetworkPool = NetworkThreadPool; var optionsProvider = Services.GetService <IOptionsProvider>(); NetworkThreadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(optionsProvider.AlexOptions.NetworkOptions.NetworkThreads.Value, ThreadType.Background, "Network ThreadPool")); try { var eventDispatcher = Services.GetRequiredService <IEventDispatcher>() as EventDispatcher; eventDispatcher?.Reset(); WorldProvider provider; INetworkProvider networkProvider; IsMultiplayer = true; if (bedrock) { provider = new BedrockWorldProvider(this, serverEndPoint, profile, NetworkThreadPool, out networkProvider); } else { provider = new JavaWorldProvider(this, serverEndPoint, profile, out networkProvider) { Hostname = hostname }; } LoadWorld(provider, networkProvider); } catch (Exception ex) { Log.Error(ex, $"FCL: {ex.ToString()}"); } oldNetworkPool?.Dispose(); }
public FtlProxyServer() { int threads; int iothreads; ThreadPool.GetMinThreads(out threads, out iothreads); DedicatedThreadPool threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(Environment.ProcessorCount)); ProxyMessageHandler.FastThreadPool = threadPool; ThreadPool.GetMaxThreads(out threads, out iothreads); ThreadPool.SetMinThreads(4000, 4000); ThreadPool.SetMaxThreads(threads, 4000); List <EndPoint> remoteServers = new List <EndPoint>(); remoteServers.Add(new IPEndPoint(IPAddress.Loopback, 51234)); _server = new MiNetServer(); _server.ServerRole = ServerRole.Proxy; _server.ServerManager = new ProxyServerManager(remoteServers); }
public void Should_process_workload_across_exactly_DedicatedThreadPoolSettings_NumThreads() { var numThreads = Environment.ProcessorCount; var threadIds = new ConcurrentBag<int>(); var atomicCounter = new AtomicCounter(0); Action callback = () => { atomicCounter.GetAndIncrement(); threadIds.Add(Thread.CurrentThread.ManagedThreadId); }; using (var threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(numThreads))) { for (var i = 0; i < 1000; i++) { threadPool.QueueUserWorkItem(callback); } //spin until work is completed SpinWait.SpinUntil(() => atomicCounter.Current == 1000, TimeSpan.FromSeconds(1)); } Assert.AreEqual(numThreads, threadIds.Distinct().Count()); }
public void Should_process_workload_across_exactly_DedicatedThreadPoolSettings_NumThreads() { var numThreads = 3; var threadIds = new ConcurrentBag <int>(); var atomicCounter = new AtomicCounter(0); Action callback = () => { atomicCounter.GetAndIncrement(); threadIds.Add(Thread.CurrentThread.ManagedThreadId); }; using (var threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(numThreads))) { for (var i = 0; i < numThreads; i++) { threadPool.EnqueueWorkItem(callback); } //spin until work is completed SpinWait.SpinUntil(() => atomicCounter.Current == 1000, TimeSpan.FromSeconds(1)); } Assert.AreEqual(numThreads, threadIds.Distinct().Count()); }
public void Should_process_workload_across_AtMost_DedicatedThreadPoolSettings_NumThreads() { var numThreads = Environment.ProcessorCount; var threadIds = new ConcurrentBag <int>(); var atomicCounter = new AtomicCounter(0); Action callback = () => { atomicCounter.GetAndIncrement(); threadIds.Add(Thread.CurrentThread.ManagedThreadId); }; using (var threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(numThreads))) { for (var i = 0; i < 1000; i++) { threadPool.QueueUserWorkItem(callback); } //spin until work is completed SpinWait.SpinUntil(() => atomicCounter.Current == 1000, TimeSpan.FromSeconds(1)); } Assert.True(threadIds.Distinct().Count() <= numThreads); }
public void World_should_not_end_if_exception_thrown_in_user_callback() { var numThreads = 3; var threadIds = new ConcurrentBag<int>(); Action badCallback = () => { threadIds.Add(Thread.CurrentThread.ManagedThreadId); throw new Exception("DEATH TO THIS THREAD I SAY!"); }; Action goodCallback = () => { threadIds.Add(Thread.CurrentThread.ManagedThreadId); }; using (var threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(numThreads, TimeSpan.FromSeconds(1)))) { for (var i = 0; i < numThreads; i++) { threadPool.QueueUserWorkItem(badCallback); Thread.Sleep(20); } //sanity check Assert.AreEqual(numThreads, threadIds.Distinct().Count()); //run the job again. Should get 3 more managed thread IDs for (var i = 0; i < numThreads*10; i++) { threadPool.QueueUserWorkItem(goodCallback); Thread.Sleep(20); } } // half of thread IDs should belong to failed threads, other half to successful ones Assert.AreEqual(numThreads * 2, threadIds.Distinct().Count()); }
public void World_should_not_end_if_exception_thrown_in_user_callback() { var numThreads = 3; var threadIds = new ConcurrentBag <int>(); Action badCallback = () => { threadIds.Add(Thread.CurrentThread.ManagedThreadId); throw new Exception("DEATH TO THIS THREAD I SAY!"); }; Action goodCallback = () => { threadIds.Add(Thread.CurrentThread.ManagedThreadId); }; using (var threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(numThreads, null, TimeSpan.FromSeconds(1)))) { for (var i = 0; i < numThreads; i++) { threadPool.QueueUserWorkItem(badCallback); Thread.Sleep(20); } //sanity check Assert.AreEqual(numThreads, threadIds.Distinct().Count()); //run the job again. Should get the same thread IDs as before for (var i = 0; i < numThreads * 10; i++) { threadPool.QueueUserWorkItem(goodCallback); Thread.Sleep(20); } } // half of thread IDs should belong to failed threads, other half to successful ones Assert.AreEqual(numThreads, threadIds.Distinct().Count()); }
public SingleplayerServer(string world, Gamemode gamemode, Difficulty difficulty, Alex alex, IPEndPoint endPoint, PlayerProfile profile, DedicatedThreadPool threadPool, out NetworkProvider networkProvider) : base(alex, endPoint, profile, threadPool, out networkProvider) { Server = new OpenServer(); ReflectionHelper.SetPrivatePropertyValue( typeof(OpenServer), Server, "Endpoint", new IPEndPoint(IPAddress.Loopback, 0)); ConnectionEndpoint = Server.Endpoint; Api = ReflectionHelper.GetPrivatePropertyValue <OpenApi>(typeof(OpenServer), Server, "OpenApi"); MiNET.Worlds.AnvilWorldProvider provider = new MiNET.Worlds.AnvilWorldProvider(world); MiNETLevel = new OpenLevel( Api, Api.LevelManager, "default", provider, Api.LevelManager.EntityManager, (GameMode)gamemode, difficulty); Api.LevelManager.SetDefaultLevel(MiNETLevel); }
private static void Main(string[] args) { var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.xml")); try { AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; Console.WriteLine("Press <Enter> to start emulation..."); Console.ReadLine(); //int threads; //int iothreads; //ThreadPool.GetMaxThreads(out threads, out iothreads); //ThreadPool.SetMaxThreads(threads, 4000); //ThreadPool.GetMinThreads(out threads, out iothreads); //ThreadPool.SetMinThreads(4000, 4000); //DedicatedThreadPool threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(Environment.ProcessorCount)); DedicatedThreadPool threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(4000)); Emulator emulator = new Emulator { Running = true }; Stopwatch watch = new Stopwatch(); watch.Start(); long start = DateTime.UtcNow.Ticks; //IPEndPoint endPoint = new IPEndPoint(Dns.GetHostEntry("yodamine.com").AddressList[0], 19132); IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 19132); var sw = Stopwatch.StartNew(); for (int j = 0; j < NumberOfBots; j++) { string playerName = $"TheGrey{j + 1:D3}"; ClientEmulator client = new ClientEmulator(threadPool, emulator, DurationOfConnection, playerName, (int)(DateTime.UtcNow.Ticks - start), endPoint, RanSleepMin, RanSleepMax, RequestChunkRadius); new Thread(o => { client.EmulateClient(); }) { IsBackground = true }.Start(); if (ConcurrentSpawn) { emulator.ConcurrentSpawnWaitHandle.Set(); } emulator.ConcurrentSpawnWaitHandle.WaitOne(); long elapsed = sw.ElapsedMilliseconds; if (elapsed < TimeBetweenSpawns) { Thread.Sleep((int)(TimeBetweenSpawns - elapsed)); } sw.Restart(); } Console.WriteLine("Press <enter> to stop all clients."); Console.ReadLine(); emulator.Running = false; } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Emulation complete. Press <enter> to exit."); Console.ReadLine(); }
public MiNetServer() { ServerRole = Config.GetProperty("ServerRole", ServerRole.Full); FastThreadPool?.Dispose(); FastThreadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(Config.GetProperty("FastThreads", 100), "Fast_Thread")); }
/// <summary> /// </summary> /// <param name="numberOfBots">The number of bots to spawn.</param> /// <param name="durationOfConnection">How long (in seconds) should each individual bots stay connected.</param> /// <param name="concurrentSpawn">Should the emulator spawn bots in parallel.</param> /// <param name="batchSize">If parallel spawn, how many in each batch.</param> /// <param name="chunkRadius">The chunk radius the bots will request. Server may override.</param> /// <param name="processorAffinity">Processor affinity mask represented as an integer.</param> private static void Main(int numberOfBots = 500, int durationOfConnection = 900, bool concurrentSpawn = true, int batchSize = 5, int chunkRadius = 5, int processorAffinity = 0) { NumberOfBots = numberOfBots; DurationOfConnection = TimeSpan.FromSeconds(durationOfConnection); ConcurrentSpawn = concurrentSpawn; ConcurrentBatchSize = batchSize; RequestChunkRadius = chunkRadius; var currentProcess = Process.GetCurrentProcess(); currentProcess.ProcessorAffinity = processorAffinity <= 0 ? currentProcess.ProcessorAffinity : (IntPtr)processorAffinity; var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "log4net.xml"))); Console.ResetColor(); Console.BackgroundColor = ConsoleColor.DarkGreen; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(MiNetServer.MiNET); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; try { AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; Console.WriteLine("Press <Enter> to start emulation..."); Console.ReadLine(); var threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(Environment.ProcessorCount)); var emulator = new Emulator { Running = true }; long start = DateTime.UtcNow.Ticks; //IPEndPoint endPoint = new IPEndPoint(Dns.GetHostEntry("yodamine.com").AddressList[0], 19132); var endPoint = new IPEndPoint(IPAddress.Loopback, 19132); Task.Run(() => { var sw = Stopwatch.StartNew(); for (int j = 0; j < NumberOfBots; j++) { string playerName = $"TheGrey{j + 1:D3}"; var client = new ClientEmulator(threadPool, emulator, DurationOfConnection, playerName, (int)(DateTime.UtcNow.Ticks - start), endPoint, RanSleepMin, RanSleepMax, RequestChunkRadius); new Thread(o => { client.EmulateClient(); }) { IsBackground = true }.Start(); if (ConcurrentSpawn) { if (j % ConcurrentBatchSize == 0 && j != 0) { for (int i = 0; i < ConcurrentBatchSize; i++) { emulator.ConcurrentSpawnWaitHandle.WaitOne(TimeSpan.FromMilliseconds(1000)); } } continue; } emulator.ConcurrentSpawnWaitHandle.WaitOne(); long elapsed = sw.ElapsedMilliseconds; if (elapsed < TimeBetweenSpawns) { Thread.Sleep((int)(TimeBetweenSpawns - elapsed)); } sw.Restart(); } }); Console.WriteLine("Press <enter> to stop all clients."); Console.ReadLine(); emulator.Running = false; } catch (Exception e) { Console.WriteLine(e); } finally { Console.ResetColor(); } Console.WriteLine("Emulation complete. Press <enter> to exit."); Console.ReadLine(); }
public Alex(LaunchSettings launchSettings) { Instance = this; LaunchSettings = launchSettings; OperatingSystem = $"{System.Runtime.InteropServices.RuntimeInformation.OSDescription} ({System.Runtime.InteropServices.RuntimeInformation.OSArchitecture})"; DeviceManager = new GraphicsDeviceManager(this) { PreferMultiSampling = false, SynchronizeWithVerticalRetrace = false, GraphicsProfile = GraphicsProfile.Reach, }; DeviceManager.PreparingDeviceSettings += (sender, args) => { Gpu = args.GraphicsDeviceInformation.Adapter.Description; args.GraphicsDeviceInformation.PresentationParameters.DepthStencilFormat = DepthFormat.Depth24Stencil8; DeviceManager.PreferMultiSampling = true; }; Content = new StreamingContentManager(base.Services, "assets"); // Content.RootDirectory = "assets"; IsFixedTimeStep = false; // graphics.ToggleFullScreen(); this.Window.AllowUserResizing = true; this.Window.ClientSizeChanged += (sender, args) => { if (DeviceManager.PreferredBackBufferWidth != Window.ClientBounds.Width || DeviceManager.PreferredBackBufferHeight != Window.ClientBounds.Height) { if (DeviceManager.IsFullScreen) { DeviceManager.PreferredBackBufferWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width; DeviceManager.PreferredBackBufferHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height; } else { DeviceManager.PreferredBackBufferWidth = Window.ClientBounds.Width; DeviceManager.PreferredBackBufferHeight = Window.ClientBounds.Height; } DeviceManager.ApplyChanges(); //CefWindow.Size = new System.Drawing.Size(Window.ClientBounds.Width, Window.ClientBounds.Height); } }; JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { Converters = new List <JsonConverter>() { new Texture2DJsonConverter(GraphicsDevice) }, Formatting = Formatting.Indented }; IServiceCollection serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); Services = serviceCollection.BuildServiceProvider(); UIThreadQueue = new ConcurrentQueue <Action>(); PluginManager = new PluginManager(Services); FpsMonitor = new FpsMonitor(); Resources = Services.GetRequiredService <ResourceManager>(); ThreadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(Environment.ProcessorCount, ThreadType.Background, "Dedicated ThreadPool")); PacketFactory.CustomPacketFactory = new AlexPacketFactory(); KeyboardInputListener.InstanceCreated += KeyboardInputCreated; }
public void SetUp() { Pool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(Environment.ProcessorCount)); Scheduler = new DedicatedThreadPoolTaskScheduler(Pool); Factory = new TaskFactory(Scheduler); }