private void btnStart_Click(object sender, EventArgs e) { try { btnStart.Enabled = false; btnStop.Enabled = true; if (oThread == null) { oThread = new System.Threading.Thread(StartListener); oThread.IsBackground = true; oThread.Start(); } if (oUDPServerThread == null) { oUDPServerThread = new System.Threading.Thread(StartUDPServer); oUDPServerThread.IsBackground = true; oUDPServerThread.Start(); } } catch (Exception ex) { Console.WriteLine(ex.Message); btnStart.Enabled = !btnStart.Enabled; btnStop.Enabled = !btnStop.Enabled; MessageBox.Show(ex.Message); } }
public static DateTime GetCubeLastSchemaUpdateDate() { DateTime dtTemp = DateTime.MinValue; Exception exDelegate = null; string sServerName = Context.CurrentServerID; string sDatabaseName = Context.CurrentDatabaseName; string sCubeName = GetCurrentCubeName(); System.Threading.Thread td = new System.Threading.Thread(delegate() { try { Microsoft.AnalysisServices.Server oServer = new Microsoft.AnalysisServices.Server(); oServer.Connect("Data Source=" + sServerName); Database db = oServer.Databases.GetByName(sDatabaseName); Cube cube = db.Cubes.FindByName(sCubeName); dtTemp = cube.LastSchemaUpdate; } catch (Exception ex) { exDelegate = ex; } } ); td.Start(); while (!td.Join(1000)) { Context.CheckCancelled(); } if (exDelegate != null) throw exDelegate; return dtTemp; }
private void BUT_connect_Click(object sender, EventArgs e) { if (comPort.IsOpen) { threadrun = false; comPort.Close(); BUT_connect.Text = Strings.Connect; } else { try { comPort.PortName = CMB_serialport.Text; } catch { CustomMessageBox.Show(Strings.InvalidPortName); return; } try { comPort.BaudRate = int.Parse(CMB_baudrate.Text); } catch {CustomMessageBox.Show(Strings.InvalidBaudRate); return;} try { comPort.Open(); } catch {CustomMessageBox.Show("Error Connecting\nif using com0com please rename the ports to COM??"); return;} t12 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop)) { IsBackground = true, Name = "Nmea output" }; t12.Start(); } }
public MainForm() { InitializeComponent(); try { foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { localIP = ip; break; } } udpListen = new UDPListen(new IPEndPoint(localIP, localPort)); System.Threading.ThreadStart threadStartListen; threadStartListen = new System.Threading.ThreadStart(udpListen.open); udpListen.msgReceiptEvent += new msgReceiptHandler(listen_msgReceiptEvent); threadListen = new System.Threading.Thread(threadStartListen); threadListen.Start(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void button1_Click(object sender, EventArgs e) { try { System.Threading.ThreadStart ts = delegate { CLKsFATXLib.Streams.Reader OR = Original.Reader(); CLKsFATXLib.Streams.Writer D = Destination.Writer(); OR.BaseStream.Position = 0; D.BaseStream.Position = 0; for (long i = 0; i < Original.Length; i += 0x6000) { D.Write(OR.ReadBytes(0x6000)); progressBar1.Invoke((MethodInvoker)delegate { try { progressBar1.Maximum = (int)(Original.Length >> 4); progressBar1.Value = (int)(((i >> 8) < 0) ? 0 : i >> 4); } catch { } }); } OR.Close(); D.Close(); }; System.Threading.Thread t = new System.Threading.Thread(ts); t.Start(); } catch (Exception x) { MessageBox.Show(x.Message); } }
public static String ModelDownloaded(ContentObject co) { System.Threading.ParameterizedThreadStart t = new System.Threading.ParameterizedThreadStart(ModelDownloaded_thread); System.Threading.Thread th = new System.Threading.Thread(t); th.Start(co); return "Thread fired"; }
public void Start(Action run) { Debug.Assert(!isRunning); thread = new System.Threading.Thread(new System.Threading.ThreadStart(run)); thread.Start(); }
private void BUT_connect_Click(object sender, EventArgs e) { if (comPort.IsOpen) { threadrun = false; comPort.Close(); BUT_connect.Text = Strings.Connect; MainV2.comPort.MAV.cs.MovingBase = null; } else { try { comPort.PortName = CMB_serialport.Text; } catch { CustomMessageBox.Show(Strings.InvalidPortName, Strings.ERROR); return; } try { comPort.BaudRate = int.Parse(CMB_baudrate.Text); } catch { CustomMessageBox.Show(Strings.InvalidBaudRate, Strings.ERROR); return; } try { comPort.Open(); } catch (Exception ex) { CustomMessageBox.Show("Error Connecting\nif using com0com please rename the ports to COM??\n" + ex.ToString(), Strings.ERROR); return; } t12 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop)) { IsBackground = true, Name = "Nmea base Input" }; t12.Start(); BUT_connect.Text = Strings.Stop; } }
public async void StartHostAndClient_SimpleSyncMethodSyncCallWithAsync_Success() { bool @continue = false; var thread = new System.Threading.Thread(() => { using (var host = new WcfExampleServiceHost("localhost:10000")) { host.Start(); @continue = true; while (@continue) { System.Threading.Thread.Sleep(10); } host.Close(); } }); thread.Start(); while (!@continue) { System.Threading.Thread.Sleep(10); } var client = new WcfExampleServiceAsyncClient("localhost:10000"); SimpleSyncMethodResponseModel responseSimpleSyncMethod = client.SimpleSyncMethod(new SimpleSyncMethodRequestModel { Message = "Hello World" }); Assert.IsNotNull(responseSimpleSyncMethod); Assert.AreEqual("SimpleSyncMethod: Hello World", responseSimpleSyncMethod.Message); @continue = false; thread.Join(); }
public static IAsyncOperation Package (MonoMacProject project, ConfigurationSelector configSel, MonoMacPackagingSettings settings, FilePath target) { IProgressMonitor mon = IdeApp.Workbench.ProgressMonitors.GetOutputProgressMonitor ( GettextCatalog.GetString ("Packaging Output"), MonoDevelop.Ide.Gui.Stock.RunProgramIcon, true, true); var t = new System.Threading.Thread (() => { try { using (mon) { BuildPackage (mon, project, configSel, settings, target); } } catch (Exception ex) { mon.ReportError ("Unhandled error in packaging", null); LoggingService.LogError ("Unhandled exception in packaging", ex); } finally { mon.Dispose (); } }) { IsBackground = true, Name = "Mac Packaging", }; t.Start (); return mon.AsyncOperation; }
public static void runUpload( ) { if (Properties.Settings.Default.firstrun) return; NameValueCollection postdata = new NameValueCollection(); postdata.Add("u", Properties.Settings.Default.username); postdata.Add("p", Properties.Settings.Default.password); if (!Clipboard.ContainsImage() && !Clipboard.ContainsText()) { nscrot.balloonText("No image or URL in clipboard!", 2); return; } if (!Clipboard.ContainsText()) { Image scrt = Clipboard.GetImage(); System.Threading.Thread upld = new System.Threading.Thread(( ) => { nscrot.uploadScreenshot(postdata, scrt); }); upld.SetApartmentState(System.Threading.ApartmentState.STA); upld.Start(); } else { string lURL = Clipboard.GetText(); System.Threading.Thread shrt = new System.Threading.Thread(( ) => { nscrot.shorten(lURL); }); shrt.SetApartmentState(System.Threading.ApartmentState.STA); shrt.Start(); } }
/// <summary> /// Plays the specified wav path. /// </summary> /// <param name="wavPath">The wav path.</param> public static void Play(string wavPath) { var thPlay = new System.Threading.Thread(THPlay); thPlay.IsBackground = true; threadWavPath = wavPath; thPlay.Start(); }
public override int DiscoverDynamicCategories() { _thread = new System.Threading.Thread(new System.Threading.ThreadStart(ReadEPG)); _thread.Start(); Settings.Categories.Clear(); RssLink cat = null; cat = new RssLink() { Name = "Channels", Other = "channels", Thumb = "http://arenavision.in/sites/default/files/FAVICON_AV2015.png", HasSubCategories = false }; Settings.Categories.Add(cat); cat = new RssLink() { Name = "Agenda", Other = "agenda", Thumb = "http://arenavision.in/sites/default/files/FAVICON_AV2015.png", HasSubCategories = false }; Settings.Categories.Add(cat); Settings.DynamicCategoriesDiscovered = true; return Settings.Categories.Count; }
public TravelModule() { load_RGS_table(); thOneMinCalTask = new System.Threading.Thread(section_data_1min_task); thOneMinCalTask.Start(); }
public void Start(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits) { if (!GetAvailablePorts().Contains(portName)) { throw new Exception(string.Format("Unknown serial port: {0}", portName)); } // Start the timer to empty the receive buffer (in case data smaller than MAX_RECEIVE_BUFFER is received) _bufferTimer = new Timer(); _bufferTimer.Interval = BUFFER_TIMER_INTERVAL; _bufferTimer.Elapsed += _bufferTimer_Elapsed; _bufferTimer.Start(); // Instantiate new serial port communication _serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits); // Open serial port communication _serialPort.Open(); // Check that it is actually open if (!_serialPort.IsOpen) { throw new Exception(string.Format("Could not open serial port: {0}", portName)); } _serialPort.ReadTimeout = 100; // Milliseconds _readThread = new System.Threading.Thread(ReadThread); _readThreadRunning = true; _readThread.Start(); }
static ContainerVideoAudio() { _aqEvents = new ThreadBufferQueue<Tuple<EventDelegate, Effect, Effect>>(false, true); _cThreadEvents = new System.Threading.Thread(WorkerEvents); _cThreadEvents.IsBackground = true; _cThreadEvents.Start(); }
public EventNotifyClient(string strIP,int port,bool bAutoRetry) { this.bAutoRetry = bAutoRetry; this.port = port; string[]ips=strIP.Split(new char[]{'.'}); for(int i=0;i<4;i++) ipByte[i]=System.Convert.ToByte(ips[i]); //if (bAutoRetry) //{ System.Threading.Thread th = new System.Threading.Thread(Connect_Task); th.Start(); //} //else //{ // tcp = new System.Net.Sockets.TcpClient(); // tcp.Connect(new System.Net.IPAddress(ipByte), port); // bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); // connected = true; // Console.WriteLine("NotifySerevr connected!"); // new System.Threading.Thread(ClientWork).Start(); //} }
private Socket SOCKET; //receive socket #endregion Fields #region Methods public void Begin() { connect: SOCKET = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); SOCKET.Connect(IPAddress.Parse("127.0.0.1"), 2404); Console.WriteLine("S104 establish a link successfully, try to receive..."); RCV_THREAD = new System.Threading.Thread(BeginReceive); RCV_THREAD.Start(SOCKET); while (true) { System.Threading.Thread.Sleep(4000); this.Send_UFram(Uflag.testfr_active); if (RCVD_NUM >= 20000) { SOCKET.Shutdown(SocketShutdown.Receive); RCV_THREAD.Abort(); System.Threading.Thread.Sleep(4000); SOCKET.Shutdown(SocketShutdown.Send); SOCKET.Dispose(); RCVD_NUM = 0; goto connect; } if (DateTime.Now - lastTime > new TimeSpan(0, 0, 4)) { this.Send_SFram(RCVD_NUM); Console.WriteLine("overtime send S fram..."); } } }
public void StartTheApplication() { this.console = new FakeConsole(); var taskList = new TaskList(console); this.applicationThread = new System.Threading.Thread(() => taskList.Run()); applicationThread.Start(); }
private void startPreview() { #region Create capture object if it is not already created if (_capture == null) { try { _capture = new Capture(); } catch (NullReferenceException excpt) { MessageBox.Show(excpt.Message); } } #endregion #region Start the capture process and display in the preview window if (_capture != null) { //start the capture //Application.Idle += ProcessFrame; captureEnabled = true; System.Threading.Thread capThread = new System.Threading.Thread(new System.Threading.ThreadStart(captureThread)); capThread.Start(); } #endregion }
// Insert / remove threads must be executed on a different thread as they are called within WndProc(). // System.Windows.Forms.Invoke also wont work as we are within WndProc at the time. // QueryRemove does not use the thread as it requires an immediate response for the application to allow removal, just // dont call any COM stuff when responding to a QueryRemove public DriveDetector( Control control ) { mControl = control; mControlHandle = mControl.Handle; mEventHandlerThread = new System.Threading.Thread( new System.Threading.ThreadStart( OnEventHandlerThreadStart ) ); mEventHandlerThread.Start(); }
public void Run() { if ((Site == null) || (Site.ID < 1)) { return; } if ((MailTo == "") || (Subject == "") || (Body == "")) { new Log("System").Write("Send Email: MailTo, Subject or Body parameters error."); return; } EmailServer_From = Site.SiteOptions["Opt_EmailServer_From"].Value.ToString(); EmailServer_EmailServer = Site.SiteOptions["Opt_EmailServer_EmailServer"].Value.ToString(); EmailServer_User = Site.SiteOptions["Opt_EmailServer_UserName"].Value.ToString(); EmailServer_Password = Site.SiteOptions["Opt_EmailServer_Password"].Value.ToString(); if ((EmailServer_From == "") || (EmailServer_EmailServer == "") || (EmailServer_User == "")) { new Log("System").Write("Send Email: Read EmailServer configure fail."); return; } lock (this) // 确保临界区被一个 Thread 所占用 { thread = new System.Threading.Thread(new System.Threading.ThreadStart(Do)); thread.IsBackground = true; thread.Start(); } }
public void Run() { //if ((ElectronTicket_HPCQ_Getway == "") || (ElectronTicket_HPCQ_UserName == "") || (ElectronTicket_HPCQ_UserPassword == "")) //{ // log.Write("ElectronTicket_XGCQ Task 参数配置不完整."); // return; //} // 已经启动 if (State == 1) { return; } lock (this) // 确保临界区被一个 Thread 所占用 { State = 1; gCount1 = 0; thread = new System.Threading.Thread(new System.Threading.ThreadStart(Do)); thread.IsBackground = true; thread.Start(); log.Write("ElectronTicket_XGCQ Task Start."); } }
private async void ActionWindowLoaded(object sender, RoutedEventArgs e) { if (count == 0) { id = Properties.Settings.Default.UserID; //ClientNameTextBox.Text = id; Active = true; Thread = new System.Threading.Thread(() => { Connection = new HubConnection(Host); Proxy = Connection.CreateHubProxy("SignalRMainHub"); Proxy.On<string, string>("addmessage", (name, message) => OnSendData(DateTime.Now.ToShortTimeString()+" ["+ name + "]\t " + message)); Proxy.On("heartbeat", () => OnSendData("Recieved heartbeat <3")); Proxy.On<HelloModel>("sendHelloObject", hello => OnSendData("Recieved sendHelloObject " + hello.Molly + " " + hello.Age)); Connection.Start(); while (Active) { System.Threading.Thread.Sleep(10); } }) { IsBackground = true }; Thread.Start(); count++; } }
protected void SendNonQuery(string stmt) { var pts = new System.Threading.ParameterizedThreadStart(_SendNonQuery); System.Threading.Thread t = new System.Threading.Thread(pts); t.Start(stmt); t.Join(); }
public byte[] sendBuffer = null;//Send buffer public socket(String ipAddress) { ip = ipAddress; sendBuffer = new byte[1024];//Send buffer //c# automatic assigesd to 0 try { //创建一个Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); System.Threading.Thread tt = new System.Threading.Thread(delegate() { //连接到指定服务器的指定端口 //方法参考:http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.connect.aspx try { clientSocket.Connect(ip, port); } catch(Exception ee) { MessageBox.Show(ee.Message); } }); tt.Start(); } catch (Exception e) { MessageBox.Show(e.Message + "\r\n From:" + this); } }
public void reConnect() { clientSocket.Close(); clientSocket = null; sendBuffer = new byte[1024];//Send buffer //c# automatic assigesd to 0 try { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); System.Threading.Thread tt = new System.Threading.Thread(delegate() { try { clientSocket.Connect(ip, port); } catch (Exception ee) { //MessageBox.Show(ee.Message + "\r\n From:" + this); } }); tt.Start(); } catch (Exception e) { //MessageBox.Show(e.Message + "\r\n From:" + this); } }
private void Ajouter_Click(object sender, EventArgs e) { System.Threading.Thread monthread = new System.Threading.Thread(new System.Threading.ThreadStart(Ajout)); monthread.Start(); this.Close(); LoadPerso(); }
public MainWindow() { InitializeComponent(); this.IsPostPanelExpand = true; this.IsFunctionPanelExpand = true; this.IsMessagePostPanelExpand = true; this.AuthPanel.OkButton.Click += new RoutedEventHandler(OkButton_Click); this.AuthPanel.PrevButton.Click += new RoutedEventHandler(PrevButton_Click); this.AuthPanel.NextButton.Click += new RoutedEventHandler(NextButton_Click); this.ReplyPanel.ReplyButton.Click += new RoutedEventHandler(ReplyPanelReplyButton_Click); this.ReplyPanel.CancelButton.Click += new RoutedEventHandler(ReplyPanelCancelButton_Click); #region Task Tray int ScreenWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width; int Screenheigth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height; int AppWidth = (int)this.Width; int AppHeight = (int)this.Height; Canvas.SetLeft(this, ScreenWidth - AppWidth); //ScreenWidth / 2 - AppWidth / 2; Canvas.SetTop(this, Screenheigth - AppHeight); //Screenheigth / 2 - AppHeight / 2; this.StateChanged += new EventHandler(MainWindow_StateChanged); this.taskIcon = new System.Windows.Forms.NotifyIcon(); this.taskIcon.Visible = true; this.taskIcon.Icon = Properties.Resources.YammyyIcon; this.taskIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(taskIcon_MouseClick); this.taskIcon.ContextMenu = new System.Windows.Forms.ContextMenu(); System.Windows.Forms.MenuItem item = new System.Windows.Forms.MenuItem("&Exit", taskIconItemExit_Click); this.taskIcon.ContextMenu.MenuItems.Add(item); #endregion System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(InitialCheck)); th.Start(); }
public webclient(Stream netstream, string path) { Path = path; clientStream = netstream; System.Threading.Thread mythread = new System.Threading.Thread(new System.Threading.ThreadStart(thetar)); mythread.Start(); }
private void Form1_Load(object sender, EventArgs e) { td = new System.Threading.Thread(LoadData); td.Start(); }
private void BUT_connect_Click(object sender, EventArgs e) { saveconfig(); if (threadrun) { threadrun = false; BUT_connect.Text = "Connect"; tracker.Close(); foreach (Control ctl in Controls) { if (ctl.Name.StartsWith("TXT_")) { ctl.Enabled = true; } if (ctl.Name.StartsWith("CMB_")) { ctl.Enabled = true; } } BUT_find.Enabled = true; //CustomMessageBox.Show("Disconnected!"); return; } if (tracker != null && tracker.ComPort != null && tracker.ComPort.IsOpen) { tracker.ComPort.Close(); } if (CMB_interface.Text == interfaces.Maestro.ToString()) { tracker = new ArdupilotMega.Antenna.Maestro(); } if (CMB_interface.Text == interfaces.ArduTracker.ToString()) { tracker = new ArdupilotMega.Antenna.ArduTracker(); } if (CMB_interface.Text == interfaces.DegreeTracker.ToString()) { tracker = new ArdupilotMega.Antenna.DegreeTracker(); } try { tracker.ComPort = new SerialPort() { PortName = CMB_serialport.Text, BaudRate = int.Parse(CMB_baudrate.Text) }; } catch (Exception ex) { CustomMessageBox.Show("Bad Port settings " + ex.Message); return; } try { tracker.PanStartRange = int.Parse(TXT_panrange.Text) / 2 * -1; tracker.PanEndRange = int.Parse(TXT_panrange.Text) / 2; tracker.TrimPan = TRK_pantrim.Value; tracker.TiltStartRange = int.Parse(TXT_tiltrange.Text) / 2 * -1; tracker.TiltEndRange = int.Parse(TXT_tiltrange.Text) / 2; tracker.TrimTilt = TRK_tilttrim.Value; tracker.PanReverse = CHK_revpan.Checked; tracker.TiltReverse = CHK_revtilt.Checked; tracker.PanPWMRange = int.Parse(TXT_pwmrangepan.Text); tracker.TiltPWMRange = int.Parse(TXT_pwmrangetilt.Text); tracker.PanPWMCenter = int.Parse(TXT_centerpan.Text); tracker.TiltPWMCenter = int.Parse(TXT_centertilt.Text); } catch (Exception ex) { CustomMessageBox.Show("Bad User input " + ex.Message); return; } if (tracker.Init()) { if (tracker.Setup()) { if (TXT_centerpan.Text != tracker.PanPWMCenter.ToString()) { TXT_centerpan.Text = tracker.PanPWMCenter.ToString(); } if (TXT_centertilt.Text != tracker.TiltPWMCenter.ToString()) { TXT_centertilt.Text = tracker.TiltPWMCenter.ToString(); } tracker.PanAndTilt(0, 0); foreach (Control ctl in Controls) { if (ctl.Name.StartsWith("TXT_")) { ctl.Enabled = false; } if (ctl.Name.StartsWith("CMB_")) { ctl.Enabled = false; } } //BUT_find.Enabled = false; t12 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop)) { IsBackground = true, Name = "Antenna Tracker" }; t12.Start(); } } BUT_connect.Text = "Disconnect"; }
private void emailSubscriptionConnection_OnNotificationEvent(object sender, NotificationEventArgs args) { try { foreach (var notificationEvent in args.Events) { if (notificationEvent is ItemEvent) // event was an item event { var itemEvent = (ItemEvent)notificationEvent; var message = EmailMessage.Bind(EmailHelper.InstanceOf.GetEmailService, itemEvent.ItemId, EmailHelper.EmailProperties ); var parentFolder = itemEvent.ParentFolderId; switch (itemEvent.EventType) { case EventType.Status: break; case EventType.NewMail: var newMailThread = new System.Threading.Thread(x => ProcessNewMail(message)); newMailThread.Start(); break; case EventType.Deleted: break; case EventType.Modified: break; case EventType.Moved: // break; case EventType.Copied: //EmailHelper.InstanceOf.RewriteSender(message); break; case EventType.Created: break; case EventType.FreeBusyChanged: break; default: throw new Exception("Invalid value for EventType"); } } else // the event was a folder event { var folderEvent = (FolderEvent)notificationEvent; switch (folderEvent.EventType) { case EventType.Status: //break; case EventType.NewMail: //break; case EventType.Deleted: //break; case EventType.Modified: //break; case EventType.Moved: //break; case EventType.Copied: //break; case EventType.Created: //break; case EventType.FreeBusyChanged: break; default: throw new Exception("Invalid value for EventType"); } } } } catch (Exception exception) { eventLog.WriteEntry(string.Format("{0}\r\nSource: {1}\r\nStack: {2}", exception.Message, exception.Source, exception.StackTrace), EventLogEntryType.Error); } }
public static void StartService() { string sharedFilePathFile = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\AreaParty\sharedFilePathInfor.audio"; transferinformation.Action.readSharedFileAndParse(ref sharedFilePathFile, ref sharedFileList); System.Threading.Thread thread = new System.Threading.Thread(MonitoringSys); thread.IsBackground = true; thread.Start(); System.Threading.Thread thread1 = new System.Threading.Thread(MonitoringProcesses); thread1.IsBackground = true; thread1.Start(); System.Threading.Thread thread2 = new System.Threading.Thread(TransferMonitorData); thread2.IsBackground = true; thread2.Start(); //bool run = false; //while (!run) //{ // System.Threading.Thread thread2 = new System.Threading.Thread(TransferMonitorData); // thread2.IsBackground = true; // try // { // thread2.Start(); // run = true; // } // catch (SocketException e) // { // thread2.Abort(); // AreaParty.function.pcapp.PCApp.Close("127.0.0.1", 7777); // //thread2.Start(); // } //} IPEndPoint localIP = new IPEndPoint(IPAddress.Any, ConfigResource.PCINFO_PORT); TcpListener listener = new TcpListener(localIP); //try //{ listener.Start(); //} //catch (SocketException) //{ // //listener. // //localIP = new IPEndPoint(IPAddress.Any, ConfigResource.PCINFO_PORT); // //listener = new TcpListener(localIP); // //listener. //} Console.WriteLine("Action Server is listening..."); while (isRun) { TcpClient remoteClient = listener.AcceptTcpClient(); Console.WriteLine("Action Server is connected..."); int RecvBytes = 0; byte[] RecvBuf = new byte[1024]; string messageGet = null; try { RecvBytes = remoteClient.Client.Receive(RecvBuf); if (RecvBytes <= 0) { Console.WriteLine("Action socket 被动关闭"); continue; } messageGet = Encoding.UTF8.GetString(RecvBuf, 0, RecvBytes); Console.WriteLine("Action Message: {0}", messageGet); RequestMessageFormat request = JsonHelper.DeserializeJsonToObject <RequestMessageFormat>(messageGet); ReturnMessageFormat returnMessage = new ReturnMessageFormat(); switch (request.name) { case Order.get_areaparty_path: returnMessage.data = null; returnMessage.message = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\AreaParty\\"; returnMessage.status = 200; break; case Order.ownProgressAction_name: if (request.command == Order.ownProgressAction_Close) { StopService(); } //transferinformation.Action.CloseProcess(System.Diagnostics.Process.GetCurrentProcess().Id); break; case Order.processAction_name: if (request.command == Order.processAction_command) { returnMessage = transferinformation.Action.CloseProcess(int.Parse(request.param)); } break; case Order.computerAction_name: if (request.command == Order.computerAction_command_reboot) { transferinformation.Action.RebootComputer(); } else if (request.command == Order.computerAction_command_shutdown) { transferinformation.Action.shutdownComputer(); } break; case Order.fileAction_name: switch (request.command) { case Order.fileAction_share_command: SharedFilePathFormat sharedFile = JsonHelper.DeserializeJsonToObject <SharedFilePathFormat>(request.param); returnMessage = transferinformation.Action.AddSharedFile(ref sharedFile, ref sharedFileList, ref sharedFilePathFile); break; case Order.fileAction_open_command: { // 此处是打开文件代码 } break; case Order.fileOrFolderAction_delete_command: { // 此处是删除文件的代码 returnMessage = transferinformation.Action.DeleteFile(request.param); } break; case Order.fileOrFolderAction_rename_command: { // 此处是重命名文件的代码 string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-", System.Text.RegularExpressions.RegexOptions.IgnoreCase); returnMessage = transferinformation.Action.RenameFile(temp[1], temp[2]); } break; case Order.fileOrFolderAction_copy_command: { string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-", System.Text.RegularExpressions.RegexOptions.IgnoreCase); returnMessage = transferinformation.Action.CopyFile(temp[2], temp[1]); } break; case Order.fileOrFolderAction_cut_command: { string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-", System.Text.RegularExpressions.RegexOptions.IgnoreCase); returnMessage = transferinformation.Action.CutFile(temp[2] + @"\", temp[1]); } break; } break; case Order.folderAction_name: switch (request.command) { case Order.nasAction_add: returnMessage = NasFunction.addNasFolder(request.param); break; case Order.nasAction_delete: returnMessage = NasFunction.deleteNasFolder(request.param); break; case Order.folderAction_addtohttp_command: ReturnMessageFormat message = new ReturnMessageFormat(); string method = request.param.Substring(0, 5); //request.param = "VIDIO/AUDIO/IMAGE" + uri string path = request.param.Remove(0, 5); //request.param = uri //FileInfo Info = new FileInfo(path); try { switch (method) { case AreaParty.pages.ListName.VIDIO: MediaConfig.AddMyVideoLibrary(path); //MediaPage.videoList.Add(new MediaPage.ListBoxMediaItem { Name = Info.Name, ImagePath = "/styles/skin/item/item_video.png" }); //MediaPage.dictVideo.Add(Info.Name, path); //MediaPage..Add(new ListBoxMediaItem { Name = Info.Name, ImagePath = "/styles/skin/item/item_video.png" }); break; case AreaParty.pages.ListName.AUDIO: MediaConfig.AddMyAudioLibrary(path); break; case AreaParty.pages.ListName.IMAGE: MediaConfig.AddMyImageLibrary(path); break; } new AreaParty.function.media.MediaFunction().GetThumbnail(path); AreaParty.util.JAVAUtil.AddAlltoHttp(path); message.status = Order.success; message.message = ""; message.data = null; } catch (Exception e) { message.status = Order.failure; message.message = e.Message; message.data = null; } returnMessage = message; break; case Order.folderAction_open_command: { // 此处是打开文件夹代码 if (request.param != Order.folderAction_open_more_param) { NodeFormat root = new NodeFormat(); root.path = request.param; folderContent = transferinformation.Action.OpenFolder(root); } returnMessage = folderContent[0]; folderContent.RemoveAt(0); } break; case Order.fileOrFolderAction_delete_command: { // 此处是删除文件夹的代码 returnMessage = transferinformation.Action.DeleteFolder(request.param); } break; case Order.fileOrFolderAction_rename_command: { // 此处是重命名文件夹的代码 string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-", System.Text.RegularExpressions.RegexOptions.IgnoreCase); returnMessage = transferinformation.Action.RenameFolder(temp[1], temp[2]); } break; case Order.folderAction_add_command: { returnMessage = transferinformation.Action.CreateFolder(request.param); } break; case Order.fileOrFolderAction_copy_command: { string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-", System.Text.RegularExpressions.RegexOptions.IgnoreCase); returnMessage = transferinformation.Action.CopyFolder(temp[1], temp[2]); } break; case Order.fileOrFolderAction_cut_command: { string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-", System.Text.RegularExpressions.RegexOptions.IgnoreCase); returnMessage = transferinformation.Action.CutFolder(temp[2], temp[1]); } break; } break; case Order.diskAction_name: switch (request.command) { case Order.diskAction_get_command: returnMessage = transferinformation.Action.GetDiskList(); break; } break; case Order.appAction_name: switch (request.command) { case Order.appAction_get_command: if (request.param != Order.appAction_get_more_param) { exeContent = transferinformation.Action.GetApplicationList(); } returnMessage = exeContent[0]; exeContent.RemoveAt(0); break; } break; } byte[] messageToSend = Encoding.UTF8.GetBytes(JsonHelper.SerializeObject(returnMessage)); int i = remoteClient.Client.Send(messageToSend); Console.WriteLine("send Message: {0} ", JsonHelper.SerializeObject(returnMessage)); } catch (Exception e) { Console.WriteLine("Action socket 被动关闭" + e.Message); } remoteClient.Close(); } Console.ReadLine(); }
public static void InitAudio() { if (loopThread == null) { loops = new List <bool>(0); effectInstances = new List <SoundEffectInstance>(0); DestVolumes = new List <float[]>(0); effects = new List <SoundEffect>(0); loops = new List <bool>(0); instaceCounts = new List <int>(0); filenames = new List <string>(0); playingMoments = new List <int>(0); names = new List <string>(0); buffers = new List <byte[]>(0); streams = new List <MemoryStream>(0); emmiters = new List <Model>(0); rnd = new Random(DateTime.Now.Millisecond); loopThread = new System.Threading.Thread(() => { while (true) { /*if (true||oldTick != Program.game.ticks) * {*/ for (int i = 0; i < loops.Count; i++) { if (effectInstances[i] == null) { loops.RemoveAt(i); names.RemoveAt(i); playingMoments.RemoveAt(i); effectInstances.RemoveAt(i); DestVolumes.RemoveAt(i); emmiters.RemoveAt(i); CurrentAmbientIndex = names.IndexOf(CurrentAmbient); i--; } } for (int i = 0; i < loops.Count; i++) { if (i == Audio.CurrentAmbientIndex) { continue; } var efi = effectInstances[i]; if (efi == null) { continue; } Model target = Program.game.mainCamera.Target; if (emmiters[i] != null && target != null) { AudioEmitter emi = new AudioEmitter { Position = (emmiters[i].Location) / 200f }; if (!Single.IsNaN(emmiters[i].MinVertex.X)) { emi.Position += Vector3.Transform((emmiters[i].MinVertex + emmiters[i].MaxVertex) / 2f, emmiters[i].Rotate_matrix) / 200f; } AudioListener reci = new AudioListener { //reci.Velocity = new Vector3((float)(Program.game.mainCamera.Target.Joystick * Math.Sin(Program.game.mainCamera.Target.Rotate)), 0, (float)(Program.game.mainCamera.Target.Joystick * Math.Cos(Program.game.mainCamera.Target.Rotate))); Position = target.Location / 200f }; if (!Single.IsNaN(target.MinVertex.X)) { reci.Position += Vector3.Transform((target.MinVertex + target.MaxVertex) / 2f, target.Rotate_matrix) / 200f; } emi.Position -= reci.Position; emi.Position = Vector3.Transform(emi.Position, Program.game.mainCamera.Yaw_backwards_matrix); //emi.Position += reci.Position; reci.Position = Vector3.Zero; efi.Apply3D(reci, emi); } if (DestVolumes[i][0] < 0) { DestVolumes[i][0] *= -1f; efi.Volume = DestVolumes[i][0]; } } /* oldTick = Program.game.ticks; * }*/ } }); loopThread.Start(); } }
private void Run() { //should we run a garbage collection thread? System.Threading.Thread gcinvoker = null; if (GCThreadInterval > 0) { gcinvoker = new System.Threading.Thread(() => { while (true) { System.Threading.Thread.Sleep(GCThreadInterval); System.GC.Collect(); } }); gcinvoker?.Start(); } var threads = new System.Collections.Generic.List <WorkerThread>(); for (int i = 0; i < Nthreads_; ++i) { var wt = new WorkerThread(this, $"WT {i}", 1234 + i); threads.Add(wt); } var hangstatus = new HangStatusGroup(Nthreads_); bool keeprunning = true; while (keeprunning) { //wait a while before asking the threads how it goes. System.Threading.Thread.Sleep(1000); //ask the threads for (int i = 0; i < Nthreads_; ++i) { hangstatus.updateThread(i, threads[i].Counter); } hangstatus.showStatus(); for (int i = 0; i < Nthreads_; ++i) { TimeSpan age = hangstatus.AgeOfUpdate(i); if (age > HangtimeLimit) { System.Console.WriteLine($"Aborting thread {i} because it appears stuck."); threads[i].Abort(); keeprunning = false; } } } //stop all threads normally System.Console.WriteLine($"stopping all threads gently..."); for (int i = 0; i < Nthreads_; ++i) { threads[i].KeepRunning = false; } //join them for (int i = 0; i < Nthreads_; ++i) { threads[i].Join(); System.Console.WriteLine($"Thread {i} has stacktrace: {threads[i].StackTrace}"); } gcinvoker?.Abort(); }
/// <summary> /// Starts a Directory copy operation in another thread /// </summary> /// <param name="CopyFrom">Source and Destination</param> public static void BeginAsyncCopy(DirCopyInfo CopyFrom) { System.Threading.Thread Worker = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ThreadCopy)); CopyFrom.BaseDir = CopyFrom.Source; Worker.Start((object)CopyFrom); }
private void getVoicesInEditor() { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = Util.Config.TTS_MACOS; process.StartInfo.Arguments = "-v '?'"; try { System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref process, Util.Constants.DEFAULT_TTS_KILL_TIME)); worker.Start(); do { System.Threading.Thread.Sleep(50); } while (worker.IsAlive || !process.HasExited); if (Util.Constants.DEV_DEBUG) { Debug.Log("Finished after: " + (process.ExitTime - process.StartTime).Seconds); } if (process.ExitCode == 0) { System.Collections.Generic.List <Model.Voice> voices = new System.Collections.Generic.List <Model.Voice>(100); using (System.IO.StreamReader streamReader = process.StandardOutput) { string reply; string name; while (!streamReader.EndOfStream) { reply = streamReader.ReadLine(); if (!string.IsNullOrEmpty(reply)) { System.Text.RegularExpressions.Match match = sayRegex.Match(reply); if (match.Success) { name = match.Groups[1].ToString(); voices.Add(new Model.Voice(match.Groups[1].ToString(), match.Groups[3].ToString(), Util.Helper.AppleVoiceNameToGender(name), "unknown", match.Groups[2].ToString().Replace('_', '-'))); } } } } cachedVoices = voices.OrderBy(s => s.Name).ToList(); if (Util.Constants.DEV_DEBUG) { Debug.Log("Voices read: " + cachedVoices.CTDump()); } } else { using (System.IO.StreamReader sr = process.StandardError) { string errorMessage = "Could not get any voices: " + process.ExitCode + System.Environment.NewLine + sr.ReadToEnd(); Debug.LogError(errorMessage); } } } catch (System.Exception ex) { string errorMessage = "Could not get any voices!" + System.Environment.NewLine + ex; Debug.LogError(errorMessage); } process.Dispose(); onVoicesReady(); }
public override IEnumerator Generate(Model.Wrapper wrapper) { if (wrapper == null) { Debug.LogWarning("'wrapper' is null!"); } else { if (string.IsNullOrEmpty(wrapper.Text)) { Debug.LogWarning("'wrapper.Text' is null or empty: " + wrapper); } else { yield return(null); //return to the main process (uid) string voiceName = getVoiceName(wrapper); int calculatedRate = calculateRate(wrapper.Rate); string outputFile = getOutputFile(wrapper.Uid); System.Diagnostics.Process process = new System.Diagnostics.Process(); string args = (string.IsNullOrEmpty(voiceName) ? string.Empty : (" -v \"" + voiceName.Replace('"', '\'') + '"')) + (calculatedRate != defaultRate ? (" -r " + calculatedRate) : string.Empty) + " -o \"" + outputFile.Replace('"', '\'') + '"' + " --file-format=AIFFLE" + " \"" + wrapper.Text.Replace('"', '\'') + '"'; if (Util.Config.DEBUG) { Debug.Log("Process arguments: " + args); } process.StartInfo.FileName = Util.Config.TTS_MACOS; process.StartInfo.Arguments = args; System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref process)) { Name = wrapper.Uid.ToString() }; worker.Start(); silence = false; onSpeakAudioGenerationStart(wrapper); do { yield return(null); } while (worker.IsAlive || !process.HasExited); if (process.ExitCode == 0) { processAudioFile(wrapper, outputFile); } else { using (System.IO.StreamReader sr = process.StandardError) { string errorMessage = "Could not generate the text: " + wrapper + System.Environment.NewLine + "Exit code: " + process.ExitCode + System.Environment.NewLine + sr.ReadToEnd(); Debug.LogError(errorMessage); onErrorInfo(wrapper, errorMessage); } } process.Dispose(); } } }
public RPPCommunicator(int _Port) //18374 { if (System.IO.Directory.Exists("RPPContributions\\") == true) { string[] files = System.IO.Directory.GetFiles("RPPContributions\\"); foreach (var file in files) { try { if (file.StartsWith("RPPContributions\\RealmPlayersData") == true) { //Old version string contributorUserID = file.Split('_').Last().Replace(".txt", ""); Logger.ConsoleWriteLine("RPP File: " + file + ", was uploaded by UserID: " + contributorUserID, ConsoleColor.Yellow); Contributor contributor = ContributorDB.GetContributor(contributorUserID, new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, 18374), false); if (contributor != null) { m_DownloadedData.Enqueue(new RPPContribution(contributor, file)); } else { Logger.ConsoleWriteLine("Contributor: " + contributorUserID + " was not found", ConsoleColor.Red); } } else if (file.StartsWith("RPPContributions\\RPP_") == true) { string contributorUserID = file.Split('_')[1]; string contributorUserIP = file.Split('_')[2]; Logger.ConsoleWriteLine("RPP File: " + file + ", was uploaded by UserID: " + contributorUserID + ", on IP: " + contributorUserIP, ConsoleColor.Yellow); Contributor contributor = ContributorDB.GetContributor(contributorUserID, new System.Net.IPEndPoint(System.Net.IPAddress.Parse(contributorUserIP), 18374), false); if (contributor != null) { m_DownloadedData.Enqueue(new RPPContribution(contributor, file)); } else { Logger.ConsoleWriteLine("Contributor: " + contributorUserID + " was not found", ConsoleColor.Red); } } else { Logger.ConsoleWriteLine("Skipping file: " + file + ", does not seem to be a RPP file"); } } catch (Exception ex) { Logger.LogException(ex); } } } if (System.IO.Directory.Exists("RDContributions\\") == true) { string[] files = System.IO.Directory.GetFiles("RDContributions\\"); foreach (var file in files) { try { if (file.StartsWith("RDContributions\\RD_") == true) { string contributorUserID = file.Split('_')[1]; string contributorUserIP = file.Split('_')[2]; Logger.ConsoleWriteLine("RD File: " + file + ", was uploaded by UserID: " + contributorUserID + ", on IP: " + contributorUserIP, ConsoleColor.Yellow); Contributor contributor = ContributorDB.GetContributor(contributorUserID, new System.Net.IPEndPoint(System.Net.IPAddress.Parse(contributorUserIP), 18374), false); if (contributor != null) { m_DownloadedDataRD.Enqueue(new RPPContribution(contributor, file)); } else { Logger.ConsoleWriteLine("Contributor: " + contributorUserID + " was not found", ConsoleColor.Red); } } else { Logger.ConsoleWriteLine("Skipping file: " + file + ", does not seem to be a RD file"); } } catch (Exception ex) { Logger.LogException(ex); } } } m_ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_ServerSocket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Any, _Port)); //m_TCPListener = new TcpListener(System.Net.IPAddress.Any, _Port); m_ListenerThread = new System.Threading.Thread(new System.Threading.ThreadStart(ListenerThread)); m_ListenerThread.Start(); }
private void InitializeCommandProxy() { // Initialize the command proxy from the current solution's package var dte = (DTE)GetService(typeof(DTE)); var solutionPath = dte.Solution.FullName; XenkoCommandsProxy.InitialzeFromSolution(solutionPath); // Get General Output pane (for error logging) var generalOutputPane = GetGeneralOutputPane(); // If a package is associated with the solution, check if the correct version was found var xenkoPackageInfo = XenkoCommandsProxy.CurrentPackageInfo; if (xenkoPackageInfo.ExpectedVersion != null && xenkoPackageInfo.ExpectedVersion != xenkoPackageInfo.LoadedVersion) { if (xenkoPackageInfo.ExpectedVersion < XenkoCommandsProxy.MinimumVersion) { // The package version is deprecated generalOutputPane.OutputStringThreadSafe($"Could not initialize Xenko extension for package with version {xenkoPackageInfo.ExpectedVersion}. Versions earlier than {XenkoCommandsProxy.MinimumVersion} are not supported. Loading latest version {xenkoPackageInfo.LoadedVersion} instead.\r\n"); generalOutputPane.Activate(); } else if (xenkoPackageInfo.LoadedVersion == null) { // No version found generalOutputPane.OutputStringThreadSafe("Could not find Xenko SDK directory."); generalOutputPane.Activate(); // Don't try to create any services return; } else { // The package version was not found generalOutputPane.OutputStringThreadSafe($"Could not find SDK directory for Xenko version {xenkoPackageInfo.ExpectedVersion}. Loading latest version {xenkoPackageInfo.LoadedVersion} instead.\r\n"); generalOutputPane.Activate(); } } // Initialize the build monitor, that will display BuildEngine results in the Build Output pane. // Seems like VS2015 display <Exec> output directly without waiting end of execution, so no need for all this anymore! // TODO: Need to find a better way to detect VS version? int visualStudioVersion; if (!int.TryParse(dte2.Version.Split('.')[0], out visualStudioVersion)) { visualStudioVersion = 12; } if (visualStudioVersion < 14) { buildLogPipeGenerator = new BuildLogPipeGenerator(this); try { // Start PackageBuildMonitorRemote in a separate app domain if (buildMonitorDomain != null) { AppDomain.Unload(buildMonitorDomain); } buildMonitorDomain = XenkoCommandsProxy.CreateXenkoDomain(); XenkoCommandsProxy.InitialzeFromSolution(solutionPath, buildMonitorDomain); var remoteCommands = XenkoCommandsProxy.CreateProxy(buildMonitorDomain); remoteCommands.StartRemoteBuildLogServer(new BuildMonitorCallback(), buildLogPipeGenerator.LogPipeUrl); } catch (Exception e) { generalOutputPane.OutputStringThreadSafe($"Error loading Xenko SDK: {e}\r\n"); generalOutputPane.Activate(); // Unload domain right away AppDomain.Unload(buildMonitorDomain); buildMonitorDomain = null; } } // Preinitialize the parser in a separate thread var thread = new System.Threading.Thread( () => { try { XenkoCommandsProxy.GetProxy(); } catch (Exception ex) { generalOutputPane.OutputStringThreadSafe($"Error Initializing Xenko Language Service: {ex.InnerException ?? ex}\r\n"); generalOutputPane.Activate(); errorListProvider.Tasks.Add(new ErrorTask(ex.InnerException ?? ex)); } }); thread.Start(); }
public override void SpeakNativeInEditor(Model.Wrapper wrapper) { if (wrapper == null) { Debug.LogWarning("'wrapper' is null!"); } else { if (string.IsNullOrEmpty(wrapper.Text)) { Debug.LogWarning("'wrapper.Text' is null or empty: " + wrapper); } else { string voiceName = getVoiceName(wrapper); int calculatedRate = calculateRate(wrapper.Rate); System.Diagnostics.Process process = new System.Diagnostics.Process(); string args = (string.IsNullOrEmpty(voiceName) ? string.Empty : (" -v \"" + voiceName.Replace('"', '\'') + '"')) + (calculatedRate != defaultRate ? (" -r " + calculatedRate) : string.Empty) + " \"" + wrapper.Text.Replace('"', '\'') + '"'; if (Util.Config.DEBUG) { Debug.Log("Process arguments: " + args); } process.StartInfo.FileName = Util.Config.TTS_MACOS; process.StartInfo.Arguments = args; System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref process)) { Name = wrapper.Uid.ToString() }; worker.Start(); silence = false; onSpeakStart(wrapper); do { System.Threading.Thread.Sleep(50); if (silence && !process.HasExited) { process.Kill(); } } while (worker.IsAlive || !process.HasExited); if (process.ExitCode == 0 || process.ExitCode == -1) { //0 = normal ended, -1 = killed if (Util.Config.DEBUG) { Debug.Log("Text spoken: " + wrapper.Text); } onSpeakComplete(wrapper); } else { using (System.IO.StreamReader sr = process.StandardError) { string errorMessage = "Could not speak the text: " + wrapper + System.Environment.NewLine + "Exit code: " + process.ExitCode + System.Environment.NewLine + sr.ReadToEnd(); Debug.LogError(errorMessage); onErrorInfo(wrapper, errorMessage); } } process.Dispose(); } } }
private void refreshData() { try { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; // DateTime date1; DateTime date2; DateTime.TryParse(dateTextBox1.Text.Trim(), out date1); DateTime.TryParse(dateTextBox2.Text.Trim(), out date2); System.Threading.Thread th = new System.Threading.Thread(() => { Cursor.Current = Cursors.WaitCursor; Helper.GlobalData.windows.ShowLoad(this); try { IBLL.ICusPriceOrder bll = new BLL.CusPriceOrderBLL(); if (date1 == DateTime.MinValue) { throw new Exception("期间不正确"); } if (date2 == DateTime.MinValue) { throw new Exception("期间不正确"); } DataTable tb = bll.GetList(date1, date2); this.dataGrid1.Invoke((MethodInvoker) delegate { this.dataGrid1.DataSource = tb; if (tb.Rows.Count > 0) { sheet_no = tb.Rows[0]["sheet_no"].ToString(); System.Data.DataTable tb1; System.Data.DataTable tb2; bll.GetOrder(sheet_no, out tb1, out tb2); this.dataGrid2.DataSource = tb2; } }); } catch (Exception ex) { IvyBack.Helper.LogHelper.writeLog("refreshData", ex.ToString()); MsgForm.ShowFrom(ex); } Cursor.Current = Cursors.Default; Helper.GlobalData.windows.CloseLoad(this); }); th.Start(); } catch (Exception ex) { MsgForm.ShowFrom(ex); } finally { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; } }
public virtual void Start() { threadField.Start(); }
private void Capturing() { captureThread = new System.Threading.Thread(new System.Threading.ThreadStart(CaptureThread)); captureThread.IsBackground = true; captureThread.Start(); }
private void DownloadManager_Shown(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; CheckThread = new System.Threading.Thread(new System.Threading.ThreadStart(CheckState)); CheckThread.Start(); }
//Load form private void FormImageTextDeepLearning_Load(object sender, EventArgs e) { //Thread of load System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Progress)); t.Start(); }
private void Uploading() { uploadThread = new System.Threading.Thread(new System.Threading.ThreadStart(UploadThread)); uploadThread.IsBackground = false; uploadThread.Start(); }
private void refreshData() { try { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; DateTime date1 = Helper.Conv.ToDateTime(dateTextBox1.Text.Trim()); DateTime date2 = Helper.Conv.ToDateTime(dateTextBox2.Text.Trim()); string text = txt_cust_id.Text.Trim().Split('/')[0]; // System.Threading.Thread th = new System.Threading.Thread(() => { Cursor.Current = Cursors.WaitCursor; Helper.GlobalData.windows.ShowLoad(this); try { IBLL.IInOutBLL bll = new BLL.InOutBLL(); if (date1 == DateTime.MinValue) { throw new Exception("期间不正确"); } if (date2 == DateTime.MinValue) { throw new Exception("期间不正确"); } //退货出库 DataTable tb = bll.GetInOutList(date1, date2, text, "D"); this.dataGrid1.Invoke((MethodInvoker) delegate { this.dataGrid1.DataSource = tb; if (tb.Rows.Count > 0) { sheet_no = tb.Rows[0]["sheet_no"].ToString(); trans_no = tb.Rows[0]["trans_no"].ToString(); System.Data.DataTable tb1; System.Data.DataTable tb2; bll.GetInOut(sheet_no, trans_no, out tb1, out tb2); this.dataGrid2.DataSource = tb2; update_time = Helper.Conv.ToDateTime(tb1.Rows[0]["update_time"]); } }); } catch (Exception ex) { IvyBack.Helper.LogHelper.writeLog("refreshData", ex.ToString()); MsgForm.ShowFrom(ex); } Cursor.Current = Cursors.Default; Helper.GlobalData.windows.CloseLoad(this); }); th.Start(); } catch (Exception ex) { MsgForm.ShowFrom(ex); Helper.LogHelper.writeLog("frmSaleInSheetList->refreshData()", ex.ToString()); } finally { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; } }
static ApiResultSummary() { System.Threading.Thread thread = new System.Threading.Thread(Analize); thread.IsBackground = true; thread.Start(); }
//bouton retour private void buttonQuitter_Click(object sender, EventArgs e) { System.Threading.Thread monthread = new System.Threading.Thread(new System.Threading.ThreadStart(retour)); monthread.Start(); this.Close(); }
/// <summary> /// 刷新下载状态 /// </summary> private void RefreshList() { TotalProgressChanged(); //根据numOnce及正在下载的情况生成下载 int downloadingCount = webs.Count; for (int j = 0; j < NumOnce - downloadingCount; j++) { if (numLeft > 0) { string url = downloadItems[downloadItems.Count - numLeft].Url; //string dest = Uri.UnescapeDataString(url.Substring(url.LastIndexOf('/') + 1)); string dest = downloadItems[downloadItems.Count - numLeft].FileName; dest = ReplaceInvalidPathChars(dest, ' '); if (IsSepSave && dest.IndexOf(' ') > 0) { string sepPath = saveLocation + "\\" + dest.Substring(0, dest.IndexOf(' ')); if (!System.IO.Directory.Exists(sepPath)) { System.IO.Directory.CreateDirectory(sepPath); } dest = sepPath + "\\" + dest; } else { dest = saveLocation + "\\" + dest; } if (System.IO.File.Exists(dest)) { downloadItems[downloadItems.Count - numLeft].StatusE = DLStatus.Failed; downloadItems[downloadItems.Count - numLeft].Size = "文件已存在"; WriteErrText("moe_error.txt", url + ": 文件已存在"); j--; } else if (dest.Length > 259) { downloadItems[downloadItems.Count - numLeft].StatusE = DLStatus.Failed; downloadItems[downloadItems.Count - numLeft].Size = "路径过长"; WriteErrText("moe_error.txt", url + ": 路径过长"); j--; } else { downloadItems[downloadItems.Count - numLeft].StatusE = DLStatus.DLing; DownloadTask task = new DownloadTask(url, dest, MainWindow.IsNeedReferer(url)); webs.Add(url, task); //异步下载开始 System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Download)); thread.Start(task); } numLeft--; } else { break; } } RefreshStatus(); }
private void btnQuit_Click(object sender, EventArgs e) { if (metrhths == questions.GetLength(0)) { RightAnswer = questions[metrhths - 1, 7]; if ((RightAnswer == "1") && (Answer1.Checked == true)) { MessageBox.Show("Σωστο"); countRightAnswers++; } else if ((RightAnswer == "1") && (Answer1.Checked == false)) { MessageBox.Show("Λάθος"); if (questions[metrhths - 1, 3] == "e") { counte = counte + 1; } else if (questions[metrhths - 1, 3] == "m") { countm = countm + 1; } else if (questions[metrhths - 1, 3] == "d") { countd = countd + 1; } } if ((RightAnswer == "2") && (Answer2.Checked == true)) { MessageBox.Show("Σωστο"); countRightAnswers++; } else if ((RightAnswer == "2") && (Answer2.Checked == false)) { MessageBox.Show("Λάθος"); if (questions[metrhths - 1, 3] == "e") { counte = counte + 1; } else if (questions[metrhths - 1, 3] == "m") { countm = countm + 1; } else if (questions[metrhths - 1, 3] == "d") { countd = countd + 1; } } if ((RightAnswer == "3") && (Answer3.Checked == true)) { MessageBox.Show("Σωστο"); countRightAnswers++; } else if ((RightAnswer == "3") && (Answer3.Checked == false)) { MessageBox.Show("Λάθος"); if (questions[metrhths - 1, 3] == "e") { counte = counte + 1; } else if (questions[metrhths - 1, 3] == "m") { countm = countm + 1; } else if (questions[metrhths - 1, 3] == "d") { countd = countd + 1; } } } double average = 1.0; average = countRightAnswers / 4; string strCongratulations = ""; // if (average >= 0.5) // strCongratulations = "\nΣυγχαρητήρια πέρασες!"; tha mporousame na allaksoume to mhnuma DialogResult res = MessageBox.Show("Συνολικές Ερωτήσεις : " + 4 + "\nΣωστές Ερωτήσεις : " + countRightAnswers.ToString() + "\nΠοσοστό επιτυχίας : " + (average * 100).ToString("F") + " %\n" + strCongratulations); System.Console.WriteLine(counte); System.Console.WriteLine(countm); System.Console.WriteLine(countd); double sume;//starts calculate the weakness double summ; double sumd; string weakness = "n"; sume = counte * 3; summ = countm * 2; sumd = countd * 1.6; double max = sume; if (max < summ) { max = summ; } if (max < sumd) { max = sumd; } if (max == sume) { weakness = "e"; } if (max == summ) { weakness = "m"; } if (max == sumd) { weakness = "d"; } System.Console.WriteLine("------------------"); System.Console.WriteLine(sume); System.Console.WriteLine(summ); System.Console.WriteLine(sumd); System.Console.WriteLine(max); System.Console.WriteLine("------------------"); if (sume == 0 && summ == 0 && sumd == 0) { weakness = "n"; System.Console.WriteLine("7"); } con.Open(); string s2; s2 = "select userid,chap2weak from elearningdb.results where userid='" + userid + "' "; mcd = new MySqlCommand(s2, con); mdr = mcd.ExecuteReader(); if (mdr.Read()) { con.Close(); con.Open(); MySqlCommand cmd6 = con.CreateCommand(); cmd6.CommandText = "Update results set chap2weak='" + weakness + "' where userid='" + userid + "' ;"; cmd6.ExecuteNonQuery(); con.Close(); } else { con.Close(); con.Open(); MySqlCommand cmd3 = con.CreateCommand(); cmd3.CommandText = "INSERT INTO results (userid,chap2weak) VALUES ('" + userid + "','" + weakness + "') "; cmd3.ExecuteNonQuery(); con.Close(); } MySqlCommand cmd2 = con.CreateCommand(); string username = LogInForm.username_s; con.Open(); string s1; double test1grade = 0.0; s1 = "select test2 from elearningdb.results where userid='" + userid + "' AND test2>=0 ;"; mcd = new MySqlCommand(s1, con); mdr = mcd.ExecuteReader(); if (mdr.Read()) { string y = mdr.GetString("test2"); Double.TryParse(y, out test1grade); } con.Close(); //con.Open(); //MySqlCommand cmd = con.CreateCommand(); //cmd.CommandText = "INSERT INTO results (test1) VALUES ('" + telikosvathmos + "')"; //cmd.ExecuteNonQuery(); //con.Close(); con.Open(); MySqlCommand cmd = con.CreateCommand(); s = "Select * From elearningdb.results as rs Inner Join users as u on rs.userid=u.userid Where u.username='******' AND test2>=0;"; mcd = new MySqlCommand(s, con); mdr = mcd.ExecuteReader(); if (mdr.Read()) { cmd.CommandText = "UPDATE results SET test2='" + (test1grade + (average * 100)) / 2 + "' where userid='" + userid + "'; "; Console.WriteLine(" είμαι εδώ 1! " + (test1grade + (average * 100))); } else { cmd.CommandText = "Update results SET test2 = '" + (average * 100) + "'where userid='" + userid + "';"; Console.WriteLine(" είμαι εδώ 2!" + userid + " bathmos:" + (average * 100)); } con.Close(); System.Collections.ArrayList counter = new System.Collections.ArrayList(); counter.Add(count1); counter.Add(count2); try { con.Open(); cmd.ExecuteNonQuery(); con.Close(); if (res == DialogResult.OK) { System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(OpenTestMenu)); this.Close(); t.Start(); } toolStripStatusLabel.Text = "Record Insert Succefully"; } catch (Exception) { toolStripStatusLabel.Text = "Query execution error"; } }
/// <summary> /// すべてを数式として貼り付け /// 例外処理しといた方が安心? /// </summary> public static void Run(Excel.Workbook book) { //とても動作が遅いので改良の余地あり //currentで見ているセル単体と、その右のセル単体であるnextの値を比べて等しければ //その結合セル内にはすべて等しいものが入っていると考えて飛ばします //空白のセルなんかも全部飛ばします //一回String型配列に入れてから、それで結合するセルを確認したほうが圧倒的に速くなる気がします //(基本的に左右と異なる名前が入っているセルがおかしい(数式として入っていない)ためそれを確認すればいい) //つまりif文での判定対象がrangeとかcellだから遅いのでString型配列に入れてからそれで判定すればいいかもしれないということ book.Application.ScreenUpdating = false; MainForm._MainFormInstance.inProrgamUse = true; int Rows = MainForm._MainFormInstance.startaddr_row, Columns = 3; Excel.Worksheet jobsheet; // 操作中のアプリケーション Excel.Sheets sheets; sheets = book.Worksheets; jobsheet = (Excel.Worksheet)sheets.get_Item(sheets.getSheetIndex("仕事シフト")); Excel.Range current = jobsheet.Cells[Rows, Columns]; //セル単体です Excel.Range next = jobsheet.Cells[Rows, Columns + 1]; Excel.Range wholeRange = null; //結合されたセル全体です string value = ""; Stopwatch sw = new Stopwatch(); sw.Start(); for (Rows = MainForm._MainFormInstance.startaddr_row; Rows < MainForm._MainFormInstance.jobtype; Rows++) { //チェックボックスの値によって、途中でメッセージを表示するかどうかを決めています if (MainForm._MainFormInstance.APFCheckBoxValue) { if (Rows % 100 == 0) { sw.Stop(); book.Application.ScreenUpdating = true; MessageBox.Show(Rows / 100 + "00行目まで終わりました\r\nここまでの合計処理時間は" + sw.ElapsedMilliseconds + "ミリ秒です"); book.Application.ScreenUpdating = false; sw.Start(); } } for (Columns = 3; Columns < 93; Columns++) { current = jobsheet.Cells[Rows, Columns]; //if (current.MergeCells) //セルの結合判定、なぜかコメントアウトされてたけど、これをコメントアウトしたから処理が長くなった可能性。。。? //問題なかったらアンコメントしてください { next = jobsheet.Cells[Rows, Columns + 1]; if (current.get_Value() == null || current.get_Value().ToString() == "")//空白判定、空白分だけ右に移動します { Columns = Columns + current.MergeArea.Columns.Count; Columns--; } else { if (next.get_Value() == current.get_Value())//結合セルの最左セルcurrentが、その一つ右のセルnextと等しければ、 //数式として貼り付けされていると考え、結合分だけ飛ばします { Columns += current.MergeArea.Columns.Count; Columns--; } else //数式として貼り付けを行う場合 { value = current.get_Value().ToString(); wholeRange = current.MergeArea; //数式として貼り付け Excel.Range src = current.Worksheet.Cells[MainForm._MainFormInstance.jobtype + 100, 1]; src.Value = value; //値を数式としてsrcに src.Copy(); //クリップボードにコピー wholeRange.PasteSpecial(Excel.XlPasteType.xlPasteFormulas); System.Threading.Thread t = new System.Threading.Thread(clearClipboard); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Columns += wholeRange.Columns.Count; Columns--; } } } } } sw.Stop(); MainForm._MainFormInstance.inProrgamUse = false; book.Application.ScreenUpdating = true; MessageBox.Show("終わったよ!\r\n合計処理時間は" + sw.ElapsedMilliseconds + "ミリ秒です"); }
public void ThreadedAssert() { System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadedAssertProc)); thread.Start(); thread.Join(); }
public Form1() { InitializeComponent(); // panel1.Enabled = false; // panel2.Enabled = false; // panel3.Enabled = false; foreach (string p in SerialPort.GetPortNames()) { comboBox1.Items.Add(p); comboBox3.Items.Add(p); comboBox5.Items.Add(p); comboBox7.Items.Add(p); } System.Threading.Thread t1 = new System.Threading.Thread(delegate() { while (1 == 1) { while (flag1) { // port1.Read(buffer, 0 , 38); port1.Read(buffer, 0, 1000); System.Threading.Thread.Sleep(100); //string blah = Convert.ToString(buffer); port1.DiscardInBuffer(); main.Write(buffer, 0, 1000); System.Threading.Thread.Sleep(400); count++; Console.WriteLine("writing in port 1: " + count); } while (flag2) { // port2.Read(buffer, 0, 38); port2.Read(buffer, 0, 1000); System.Threading.Thread.Sleep(100); string blah = Convert.ToString(buffer); port2.DiscardInBuffer(); main.Write(buffer, 0, 1000); System.Threading.Thread.Sleep(100); // main.Write(blah); //main.Write(port2.ReadExisting()); count++; Console.WriteLine("writing in port 2 " + count); } while (flag3) { //port3.Read(buffer, 0, 38); port3.Read(buffer, 0, 512); System.Threading.Thread.Sleep(100); string blah = Convert.ToString(buffer); port3.DiscardInBuffer(); main.Write(buffer, 0, 512); System.Threading.Thread.Sleep(100); //main.Write(blah); // main.Write(port3.ReadExisting()); count++; Console.WriteLine("writing in port 3"); } } }); t1.Start(); }
public void ThreadedAndForget() { System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(Normal)); thread.Start(); }
public static void Main(string[] args) { try { Console.CursorVisible = false; Console.Title = "crystal"; Console.WindowWidth = 100; Console.WindowHeight = 50; Task.Factory.StartNew(() => Interop.StartArgsManager.ProcessArgs(args)); Utilities.ConsoleStyle.DrawAscii(); Utilities.ConsoleStyle.InitConsole(); Utilities.ConfigurationManager.LoadConfiguration(); MaxIdleTime = Utilities.ConfigurationManager.GetIntValue("MaximumIdleTime"); StartTime = Environment.TickCount; Console.Title = "Crystal World " + Utilities.ConfigurationManager.GetStringValue("ServerName") + " (" + Utilities.ConfigurationManager.GetStringValue("ServerID") + ")"; Globalization.I18nManager.LoadLangs(); Utilities.ConsoleStyle.Infos(I18nManager.GetText(0)); Utilities.ConsoleStyle.Infos(I18nManager.GetText(1)); Database.Manager.DatabaseManager.StartDatabase(); Utilities.ConsoleStyle.Infos(I18nManager.GetText(2)); if (Utilities.ConfigurationManager.GetBoolValue("CreateShema")) { Utilities.ConsoleStyle.Infos("Creating shema ..."); Database.Manager.DatabaseManager.InitTable(); Utilities.ConsoleStyle.Infos("Shema created !"); } Utilities.ConsoleStyle.Infos(I18nManager.GetText(3)); World.Handlers.AccountHandler.RegisterMethod(); World.Handlers.GameHandler.RegisterMethod(); World.Handlers.BasicHandler.RegisterMethod(); World.Handlers.ItemHandler.RegisterMethod(); World.Handlers.NpcHandler.RegisterMethod(); World.Handlers.ZaapHandler.RegisterMethod(); World.Handlers.FriendHandler.RegisterMethod(); World.Handlers.EnemiesHandler.RegisterMethod(); World.Handlers.DialogHandler.RegisterMethod(); World.Handlers.ExchangeHandler.RegisterMethod(); World.Handlers.PartyHandler.RegisterMethod(); World.Handlers.SpellHandler.RegisterMethod(); World.Handlers.FightHandler.RegisterMethod(); World.Handlers.GuildHandler.RegisterMethod(); World.Handlers.MountHandler.RegisterMethod(); World.Handlers.EmoteHandler.RegisterMethod(); Utilities.ConsoleStyle.Infos(I18nManager.GetText(4)); Utilities.ConsoleStyle.Infos(I18nManager.GetText(5)); World.Game.Jobs.JobManager.LoadJobs(); Utilities.ConsoleStyle.Infos(I18nManager.GetText(6)); Utilities.ConsoleStyle.Infos(I18nManager.GetText(7)); Database.Cache.AccountDataCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.AccountDataCache.Cache.Count.ToString() + " @Accounts data loaded"); Database.Cache.BreedCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.BreedCache.Cache.Count.ToString() + " @Breeds data loaded"); Database.Cache.OriginalBreedStartMapCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.OriginalBreedStartMapCache.Cache.Count.ToString() + " @Original maps loaded"); Database.Cache.IncarnamTeleporterCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.IncarnamTeleporterCache.Cache.Count.ToString() + " @Incarnam teleporters loaded"); Database.Cache.GuildCreatorLocationCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.GuildCreatorLocationCache.Cache.Count.ToString() + " @Guild creator loaded"); Database.Cache.GuildCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.GuildCache.Cache.Count.ToString() + " @Guild loaded"); Utilities.ConsoleStyle.Infos("Loading @maps@ ..."); Utilities.ConsoleStyle.EnableLoadingSymbol(); Database.Cache.MapCache.Init(); Utilities.ConsoleStyle.DisabledLoadingSymbol(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.MapCache.Cache.Count + " @Maps loaded !"); Database.Cache.IODataCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.IODataCache.Cache.Count.ToString() + " @Interactive object loaded"); Database.Cache.DungeonRoomCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.DungeonRoomCache.Cache.Count + " @Dungeon rooms loaded !"); if (Utilities.ConfigurationManager.GetBoolValue("FastLoading")) { Utilities.ConsoleStyle.Infos("Fast loading enabled !"); Utilities.ConsoleStyle.Warning("Be careful with this function, don't use it in real situation, use this only for debugging"); System.Threading.Thread triggerThread = new System.Threading.Thread(new System.Threading.ThreadStart(Database.Cache.TriggerCache.Init)); triggerThread.Start(); } else { Database.Cache.TriggerCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.TriggerCache.Cache.Count + " @Trigger loaded !"); } Database.Cache.ExpFloorCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.ExpFloorCache.Cache.Count + " @Exp floors loaded !"); if (Utilities.ConfigurationManager.GetBoolValue("FastLoading")) { System.Threading.Thread spellThread = new System.Threading.Thread(new System.Threading.ThreadStart(Database.Cache.SpellCache.Init)); spellThread.Start(); } else { Database.Cache.SpellCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.SpellCache.Cache.Count + " @Spells data loaded !"); } Database.Cache.BaseSpellCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.BaseSpellCache.Cache.Count + " @Base spells loaded !"); Database.Cache.NpcCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.NpcCache.Cache.Count + " @Npcs loaded !"); Utilities.ConsoleStyle.Infos("Loading @characters@ ..."); Utilities.ConsoleStyle.EnableLoadingSymbol(); Database.Cache.CharacterCache.Init(); Utilities.ConsoleStyle.DisabledLoadingSymbol(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.CharacterCache.Cache.Count + " @Characters loaded !"); Database.Cache.MountTemplateCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.MountTemplateCache.Cache.Count + " @Mount templates loaded !"); Database.Cache.WorldMountCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.WorldMountCache.Cache.Count + " @WorldMounts loaded !"); Database.Cache.ItemCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.ItemCache.Cache.Count + " @Items loaded !"); Database.Cache.ItemSetCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.ItemSetCache.Cache.Count + " @Item Sets loaded !"); Utilities.ConsoleStyle.Infos("Loading @world items@ ..."); Utilities.ConsoleStyle.EnableLoadingSymbol(); Database.Cache.WorldItemCache.Init(); Utilities.ConsoleStyle.DisabledLoadingSymbol(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.WorldItemCache.Cache.Count + " @WorldItems loaded !"); Utilities.ConsoleStyle.Infos("Loading @item bags@ ..."); Database.Cache.ItemBagCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.ItemBagCache.Cache.Count + " @ItemBags loaded !"); Database.Cache.NpcPositionCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.NpcPositionCache.Cache.Count + " @Npcs positions loaded !"); Database.Cache.NpcDialogCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.NpcDialogCache.Cache.Count + " @Npcs dialogs loaded !"); Database.Cache.MonstersTemplateCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.MonstersTemplateCache.Cache.Count + " @Monsters templates loaded !"); Database.Cache.MonsterLevelCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.MonsterLevelCache.Cache.Count + " @Monsters levels loaded !"); Database.Cache.DropCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.DropCache.Cache.Count + " @Drops loaded !"); Database.Cache.ZaapCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.ZaapCache.Cache.Count + " @Zaaps loaded !"); Database.Cache.PaddockCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.PaddockCache.Cache.Count + " @Paddocks loaded !"); Database.Cache.JobDataCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.JobDataCache.Cache.Count + " @Jobs loaded !"); Database.Cache.CraftCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.CraftCache.Cache.Count + " @Recipes loaded !"); Database.Cache.ShopItemCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.ShopItemCache.Cache.Count + " @Shop item loaded !"); Database.Cache.BannedAccountCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.BannedAccountCache.Cache.Count + " @Banned Account loaded !"); Database.Cache.ElitesCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.ElitesCache.Cache.Count + " @Elites level loaded !"); Database.Cache.HotelCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.HotelCache.Cache.Count + " @Hotel rooms loaded !"); Database.Cache.AuctionHouseCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.AuctionHouseCache.Cache.Count + " @Auction Houses loaded !"); Database.Cache.AuctionHouseItemsCache.Init(); Utilities.ConsoleStyle.Infos("@" + Database.Cache.AuctionHouseItemsCache.Cache.Count + " @Auction Houses Items loaded !"); Database.Cache.CharacterCache.SetToMaxLife(); Utilities.ConsoleStyle.Infos("@Restoring character life@ completed !"); Utilities.ConsoleStyle.Infos("Cache created !"); Interop.Scripting.ScriptManager.Load("Scripts"); Interop.PythonScripting.ScriptManager.Load(); Utilities.ConsoleStyle.Infos("@Scripts@ loaded !"); /* World contents enabling */ World.Manager.WorldManager.SyncMonsterLevelWithTemplate(); Utilities.ConsoleStyle.Infos("@Sync monsters@ with all levels available finished !"); World.Manager.WorldManager.SyncMapWithMonsterAvailable(); Utilities.ConsoleStyle.Infos("@Sync maps@ with all monsters available finished !"); World.Manager.WorldManager.InitServer(); Communication.Realm.Communicator.InitServer(); Communication.Rcon.RConManager.InitServer(); World.Network.World.InitAutoSave(Utilities.ConfigurationManager.GetIntValue("SaveIntervall")); Utilities.ConsoleStyle.Infos("@AutoSave@ started !"); World.Network.World.InitAutoInformationsUpdate(); World.Game.LiveActions.LiveActionManager.Initialize(); Utilities.ConsoleStyle.Infos("@LiveActions@ initialized !"); World.Game.Kolizeum.KolizeumManager.LoadMaps(); Utilities.ConsoleStyle.Infos("@" + World.Game.Kolizeum.KolizeumManager.Maps.Count + "@ Kolizeum maps loaded !"); World.Game.Kolizeum.KolizeumManager.LaunchKolizeumTask(); World.Game.Shop.ShopManager.Logger = new Utilities.BasicLogger("Datas/Shop/shop_logs" + StartTime + ".log"); LoadHelpFile(); World.Game.Admin.AdminRankManager.Initialize(); Utilities.ConsoleStyle.Infos("Admins ranks @permissions initialized@ !"); World.Game.Pvp.PvpManager.LoadNoPvpMaps(); World.Game.Exchange.ExchangeRestrictions.LoadRestrictedItems(); World.Game.Ads.AdsManager.LoadAds(); World.Game.Idle.IdleManager.Start(); Utilities.ConsoleStyle.Infos("@" + World.Game.Ads.AdsManager.Ads.Count + "@ Ads loaded !"); //World.Game.Pools.PoolManager.StartPoolsWarning(); Utilities.ConsoleStyle.Infos("@Server online !@"); Communication.NightWorld.NightWorldManager.Start(); while (true) { //TODO: Command scalar ! Console.ReadLine(); } } catch (Exception ex) { Utilities.ConsoleStyle.Error("Error : " + ex.ToString()); Console.ReadLine(); } }
public void Threaded() { System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(Normal)); thread.Start(); System.Threading.Thread.Sleep(100); }
public void ThreadedAndWait() { System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(Normal)); thread.Start(); thread.Join(); }