static void Main(string[] args) { RequestWorker requestworker = new RequestWorker(new RequestRepository()); requestworker.Start(3, 3); Thread.Sleep(30000); requestworker.Stop(); }
public static RequestWorkerSet GetDefaultWorker(DataContainer data, ILogger logger) { RequestWorker logWorker = new RequestWorker("log", new OnlyCommandPipeline(), new LogCommand(logger)); RequestWorkerSet defaultWorkerSet = new RequestWorkerSet(); defaultWorkerSet.AddRequestWorkers(logWorker); return(defaultWorkerSet); }
public void Test() { var repositoryStub = new RequestRepositoryStub(); var worker = new RequestWorker(repositoryStub); worker.Start(12, 56); Thread.Sleep(5000); worker.Stop(); Assert.Equal(repositoryStub.Requested, repositoryStub.Processed + repositoryStub.Deleted); }
private void Btn_uploadAPK_Click(object sender, EventArgs e) { if (tb_APKFile.Text == "") { return; } RequestWorker.RunWorkerAsync(); lb_status.Text = "掃描中..."; lb_status.Visible = true; toolStripProgressBar1.Visible = true; btn_uploadAPK.Enabled = false; }
/// <summary> /// Starts a new thread that writes informations about the current visit to the statistics. /// </summary> /// <param name="context"></param> public void AddVisit(HttpContext context) { if (IsStatisticEnabled) { // Bots will be ignored. if (!StatisticHelper.IsBot(context.Request)) { RequestWorker worker = new RequestWorker(this, context); Thread t = new Thread(new ThreadStart(worker.AddVisit)); t.Start(); } } }
public void CoreTest() { var commandExample = new SummCommand(); var builderExample = new ResponseBuilder(); var pipelineExample = new CommandResponsePipeline(); RequestWorker workerExample = new RequestWorker("summ", pipelineExample, commandExample, builderExample); RequestWorkerSet workerSet = new RequestWorkerSet(); workerSet.AddRequestWorkers(workerExample); WorkCore core = new WorkCore(workerSet); core.Run("summ:10,20"); Assert.AreEqual("30", commandExample.Work().GetObject <string>(VALUE_VARIABLE_NAME)); Assert.AreEqual("30", builderExample.GetResponse().Value); }
/// <summary> /// Listening for new connections, accepting them, and creating new thread for every request /// </summary> private void listen() { while (true) { try { if (RunningTasks >= 10) { Thread.Sleep(500); } else { Socket newSocket = m_listener.AcceptSocket(); //m_socket = newSocket; RequestWorker request = new RequestWorker(newSocket, ref m_runningTasks); m_newThread = new Thread(new ThreadStart(request.startRequestThread)); m_newThread.Start(); } } catch (Exception) { }; } }
public static void Main() { log.Info("Server is starting!"); //Load configuration file log.Config("Loading configuration file"); Settings = Config.loadConfig(); if (Settings == null) { log.Fatal("The server failed to start because of an invalid configuration setting. Please check the server configuration!"); log.Fatal("Press the any key to exit..."); Console.ReadKey(); Console.WriteLine(); log.Close(); return; } if (Settings.ContainsKey("logSettings")) { JObject logSettings = (JObject)Settings["logSettings"]; if (logSettings.ContainsKey("logLevel")) { var logLevel = (Level)typeof(Level).GetFields().First(x => x.Name.ToLower() == ((string)logSettings["logLevel"]).ToLower()).GetValue(null); if (logLevel != null) { log.LogLevel = logLevel; } } if (logSettings.ContainsKey("format")) { log.Format = (string)logSettings["format"]; } } log.Config("Setting up files and directories..."); try { IOSetup(); } catch (IOException e) { log.Fatal("Failed to set up files and directories."); log.Fatal(e.Message); Console.ReadKey(); Console.WriteLine(); log.Close(); return; } log.OutputStreams.Add(new AdvancingWriter(Logs("latest.log")) { Compression = true, CompressOnClose = false, Archive = Logs("{0:dd-MM-yyyy}.{2}.zip") }); //Get local IP address, if autodetect is enabled in settings. List <string> addresses = Settings["connectionSettings"]["serverAddresses"].ToObject <List <string> >(); if ((bool)Settings["connectionSettings"]["autodetect"]) { string address; using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0)) { socket.Connect("8.8.8.8", 65530); IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint; address = endPoint.Address.ToString(); addresses.Add(address); } log.Info("Detected IPv4 address to be " + address); } //Create request queue var requestQueue = new BlockingCollection <HttpListenerContext>(); // Create listener thingy. HttpListener listener = new HttpListener(); foreach (string address in addresses) { listener.Prefixes.Add("http://" + address + "/"); } ListenerThread = new Listener(listener, requestQueue, "ListenerThread", log); try { ListenerThread.Start(); } catch (HttpListenerException e) { log.Fatal("Failed to create Listener. Are you running the server in Administrator mode?."); log.Fatal(e.Message); Console.ReadKey(); Console.WriteLine(); log.Close(); return; } //Create console command thread ConsoleThread = new Thread(() => API.Threads.ConsoleCommand.main(log)) { IsBackground = true }; ConsoleThread.Start(); //Create worker threads log.Config("Creating worker threads..."); int threadCount = (int)Settings["performanceSettings"]["workerThreadCount"]; RequestWorkers = new RequestWorker[threadCount]; for (int i = 0; i < threadCount; i++) { try { var worker = new RequestWorker(CreateConnection(), requestQueue, "RequestWorker" + (i + 1), log); worker.Start(); RequestWorkers[i] = worker; } catch (MySqlException e) { log.Error("Failed to create connection for RequestWorker" + (i + 1)); log.Error(e.Message); } } log.Info("Finished setup"); // Wait until all threads are terminated foreach (var worker in RequestWorkers.Where(x => x != null)) { worker.Join(); log.Fine($"Stopped '{worker}'"); } // Exit main thread log.Info("Exiting program..."); log.Close(); }
public static void Main() { //Initialize logger LogTab Tab = new LogTab("General"); Log = Tab.GetLogger(); RequestWorker.RequestLoggerTab = new LogTab("Workers"); Log.Info("Server is starting!"); //Create default config Log.Info("Loading configuration files..."); Config.AddConfig(new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Webserver.DefaultConfig.json"))); Config.SaveDefaultConfig(); //Load the configuration file Dictionary <string, List <string> > Missing = Config.LoadConfig(); //Display all missing and/or invalid config settings, if any. if (Missing == null) { Log.Fatal("The config file could not be read. Ensure that it is a valid JSON file. Press any key to exit."); Console.ReadKey(); return; } else if (Missing.Count > 0) { Log.Fatal("Found one or more invalid or missing configuration settings;"); foreach (string Key in Missing.Keys) { if (Missing[Key].Count == 0) { Console.Write(Key); } foreach (string Key2 in Missing[Key]) { Log.Fatal(Key + "." + Key2); } } Log.Fatal("Please check the configuration file. Press any key to exit."); Console.ReadKey(); return; } //Check CORS addresses CORSAddresses = Utils.ParseAddresses(Config.GetValue("ConnectionSettings.AccessControl").ToObject <List <string> >()); List <string> Addresses = Utils.ParseAddresses(Configurator.Config.GetValue("ConnectionSettings.ServerAddresses").ToObject <List <string> >()); CORSAddresses = CORSAddresses.Concat(Addresses).ToList(); //Run inits SQLiteConnection Connection = Database.Init(); WebFiles.Init(); Redirect.Init(); //Find all API endpoints DiscoverEndpoints(); //Create Queue and launch listener Thread ListenerThread = new Thread(() => Listener.Run()); ListenerThread.Start(); //Create performance tab + watchers MonitorTab pTab = new MonitorTab("PerfMon"); RequestWorker.RequestTimeWatcher = pTab.CreateNumWatcher("Request time", ShowMin: true, ShowAverage: true, ShowMax: true); Listener.QueueSizeWatcher = pTab.CreateNumWatcher("Queue size", ShowMax: true); //Launch worker threads List <Thread> WorkerThreads = new List <Thread>(); for (int i = 0; i < (int)Config.GetValue("PerformanceSettings.WorkerThreadCount"); i++) { RequestWorker Worker = new RequestWorker((SQLiteConnection)Connection.Clone()); Thread WorkerThread = new Thread(new ThreadStart(Worker.Run)) { Name = "RequestWorker" + i }; WorkerThread.Start(); WorkerThreads.Add(WorkerThread); } //Launch maintenance thread Timer Maintenance = new Timer(new MaintenanceThread { Log = Log }.Run, null, 0, 3600 * 1000); //Wait for an exit command, then exit. foreach (Thread Worker in WorkerThreads) { Worker.Join(); } }