Esempio n. 1
1
        public MainForm()
        {
            InitializeComponent();

            m_settings = new Settings();
            LoadSettings();

            // default is HS if not selected
            m_stripHS = new Hesari(HS_BASE_ADDRESS);
            m_stripKaleva = new Kaleva(KALEVA_BASE_ADDRESS);

            if (m_settings.SourceSelection == SelectedSource.HS ||
                m_settings.SourceSelection == SelectedSource.NOT_SELECTED)
                m_currentStrip = m_stripHS;
            else
                m_currentStrip = m_stripKaleva;

            //Prepare the fade in/out threads that will be called later
            ThreadStart fadeInStart = new ThreadStart(FadeIn);
            m_fadeIn = new Thread(fadeInStart);

            ThreadStart fadeOutStart = new ThreadStart(FadeOut);
            m_fadeOut = new Thread(fadeOutStart);

            loadResources();

            nextPictureBox.Hide();
            prevPictureBox.Hide();

            this.MouseClick += new MouseEventHandler(MainForm_MouseClick);

            ResizeRedraw = true;
            SetLoadLabel(true);
            LoadCurrent();
        }
Esempio n. 2
0
 public static Thread CreateThread(ThreadStart st)
 {
     Thread t = new Thread(st);
     //t.ApartmentState = ApartmentState.STA;
     t.SetApartmentState(ApartmentState.STA);
     return t;
 }
Esempio n. 3
0
 public void StartThread()
 {
     ThreadStart threadStart = new ThreadStart(UpdateIndex);
     Thread thread = new Thread(threadStart);
     thread.IsBackground = true;//后台线程
     thread.Start();
 }
Esempio n. 4
0
	void LookingForServer()		
	{
		while(mConnected == false)
		{
			Thread.Sleep(500);
			try {
				TcpClient tcpclnt = new TcpClient();
				Debug.Log("Connecting.....");
				
				//tcpclnt.Connect("192.168.13.113",8001);
				tcpclnt.Connect(Config.ip,8001);
				// use the ipaddress as in the server program
				mConnected =true;
				
				mServerStream = tcpclnt.GetStream();
				
				ThreadStart ts = new ThreadStart(ListenServer);		
				mThreadListen = new Thread(ts);		
				mThreadListen.Start();
			}
			
			catch (Exception e) {
				Debug.Log("Error..... " + e.StackTrace);
			}
		}
		mSynchronizing = false;
	}
Esempio n. 5
0
 private void btnTrain_Click(object sender, EventArgs e)
 {
     this.status.Text = "Training...";
     ThreadStart ts = new ThreadStart(ThreadProc);
     Thread thread = new Thread(ts);
     thread.Start();
 }
Esempio n. 6
0
		public Form2(String hostPort, Form1 form1)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
			dataReadyToSend = new AutoResetEvent(false);
			refToForm1 = form1;
			// Resolve the local host.
			IPHostEntry localHost = Dns.Resolve(Dns.GetHostName());
			// Create a local end point for listening.
			IPEndPoint localEndPoint = new IPEndPoint(localHost.AddressList[0], 4001);
			// Instantiate the TCP Listener.
			tcpListener = new TcpListener(localEndPoint);
			tcpListener.Start();
			tcp = tcpListener.AcceptTcpClient();
			ethernetThreadStart = new ThreadStart(this.ThreadProcPollOnEthernet);
			pollDevicesEthernetThread = new Thread(ethernetThreadStart);
			pollDevicesEthernetThread.Name = "Listener's Receive Thread";
			pollDevicesEthernetThread.ApartmentState = System.Threading.ApartmentState.MTA;
			pollDevicesEthernetThread.Start();
		}
Esempio n. 7
0
        public MainApp(bool passed_debug_mode, string passed_version, bool passed_verbose)
        {
            //This checks if there is a new version, and if so alerts user
            ThreadStart update_Checker = new ThreadStart(this.check_updates_wrapper);
            Thread new_thread = new Thread(update_Checker);
            new_thread.Name = "6 to 4 - Update Checker";
            new_thread.Start();
            //Start the actual window
            InitializeComponent();
            //Tell all threads, amin is still running, is janky but works
            running = 2;
            //Starts animating icon while devcon is running
            ThreadStart Animation = new ThreadStart(this.animation);
            Thread animation_thread = new Thread(Animation);
            animation_thread.Name = "6 to 4 - Animation Thread";
            animation_thread.Start();

            //Set internals from passed
            internal_version = passed_version;
            internal_debug = passed_debug_mode;
            internal_verbose = passed_verbose;
            //Easter egg
            if (internal_verbose == true)
            {
                FLASHY = new Visual_Form();
                verbose_wrapper();
            }
        }
Esempio n. 8
0
 public ScrollForm()
 {
     InitializeComponent();
     closeProc = _close_mix_thread_proc;
     hideProc = _hide_mix_thread_proc;
     FormGenieExtension = new GenieExtension(this);
 }
Esempio n. 9
0
        static void Main(string[] args)
        {
            try
            {
                // Using Spring's IoC container
                ContextRegistry.GetContext();

                Spring.Messaging.Amqp.Rabbit.Listener.SimpleMessageListenerContainer container =
                     ContextRegistry.GetContext().GetObject("MessageListenerContainer") as Spring.Messaging.Amqp.Rabbit.Listener.SimpleMessageListenerContainer;
                container.Start();

                Console.Out.WriteLine("Server listening...");
                IMarketDataService marketDataService =
                    ContextRegistry.GetContext().GetObject("MarketDataGateway") as MarketDataServiceGateway;
                ThreadStart job = new ThreadStart(marketDataService.SendMarketData);
                Thread thread = new Thread(job);
                thread.Start();
                Console.Out.WriteLine("--- Press <return> to quit ---");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e);
                Console.Out.WriteLine("--- Press <return> to quit ---");
                Console.ReadLine();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Session["MainUrl"].ToString();
            }
            catch (NullReferenceException)
            {
                Response.Redirect("~/");
                return;
            }
            Debug.WriteLine(">>>> CodeQuality");

            this.sitemap = (List<string>)Session["selectedSites"];

            var ths = new ThreadStart(TestCodeQuality);
            var th = new Thread(ths);
            th.Start();

            th.Join();

            var sb = new System.Text.StringBuilder();
            CodeQualitySession.RenderControl(new System.Web.UI.HtmlTextWriter(new System.IO.StringWriter(sb)));
            string htmlstring = sb.ToString();

            Session["CodeQuality"] = htmlstring;
        }
        private void Run(ThreadStart userDelegate, ApartmentState apartmentState)
        {
            lastException = null;

            Thread thread = new Thread(
                delegate()
                    {
#if !DEBUG
                        try
                        {
#endif
                        userDelegate.Invoke();
#if !DEBUG
                        }
                        catch (Exception e)
                        {
                            lastException = e;
                        }
#endif
                    });
            thread.SetApartmentState(apartmentState);

            thread.Start();
            thread.Join();

            if (ExceptionWasThrown())
                ThrowExceptionPreservingStack(lastException);
        }
Esempio n. 12
0
        static void Main()
        {
            Program p = new Program();
            Calculator c = new Calculator();

            // Get first numeric value.
            c.FirstNumber = p.GetNumericValue();

            // Get second numeric value.
            c.SecondNumber = p.GetNumericValue();

            // TODO: Create an instance of the ThreadStart delegate passing
            //      in the Add method of the Calculator class.
            ThreadStart threadStart = new ThreadStart(c.Add);

            // TODO: Declare and create an instance of the secondary thread
            //      passing in the delegate instance.
            Thread thread = new Thread(threadStart);

            //TODO:  Start the secondary thread.
            thread.Start();

            System.Threading.Thread.Sleep(2500);

            Console.WriteLine("\nTotal values: {0}",
                c.TotalValue);

            Console.Write("\nPress any key to end.");
            Console.ReadLine();
        }
Esempio n. 13
0
        public static void Main(string[] args)
        {
            Console.WriteLine ("Starting up websocket...");
            Thread thread = null;
            WebsocketController ws = new WebsocketController ();
            ws.Setup ("ws://websocket.org", "80", "/echo", "echo.websocket.org");
            ThreadStart ts = new ThreadStart (() => {
                ws.Connect ((str) => {
                    Console.WriteLine ("OPEN");
                    ws.Send ("Message 1");
                }, (str2) => {
                    Console.WriteLine ("Received");
                    //ws.Send ("Message n");
                }, (str3)=>{ Console.WriteLine(str3); if(thread != null) thread.Join();},
                (str4)=>{ Console.WriteLine(str4); if(thread != null) thread.Join();});
            });

            thread = new Thread (ts);
            thread.Start ();
            while (true) {
                string s = Console.ReadLine ();
                if (!string.IsNullOrEmpty (s))
                    ws.Send (s);
            }
        }
Esempio n. 14
0
    private UploadFileChooserUI()
    {
        Glade.XML gxml = new Glade.XML (null, "organizer.glade", "filechooserdialog1", null);
          gxml.Autoconnect (this);
          _job = new ThreadStart(ProcessThumbnail);
          _previewthread = new Thread(_job);

          label16.WidthRequest = eventbox7.WidthRequest;

          eventbox7.ModifyBg(Gtk.StateType.Normal, bgcolor);
          eventbox8.ModifyBg(Gtk.StateType.Normal, bgcolor);
          eventbox9.ModifyBg(Gtk.StateType.Normal, bgcolor);

          filechooserdialog1.Title = "Select files to upload";
          filechooserdialog1.SetIconFromFile(DeskFlickrUI.ICON_PATH);
          filechooserdialog1.SetFilename(PersistentInformation.GetInstance().UploadFilename);
          filechooserdialog1.SelectMultiple = true;

          FileFilter imagefilter = new FileFilter();
          imagefilter.AddMimeType("image/jpeg");
          imagefilter.AddMimeType("image/png");
          filechooserdialog1.Filter = imagefilter;

          filechooserdialog1.SelectionChanged += new EventHandler(OnFileSelectedChanged);
          filechooserdialog1.FileActivated += new EventHandler(OnOpenButtonClicked);
          button10.Clicked += new EventHandler(OnOpenButtonClicked);
          button11.Clicked += new EventHandler(OnCancelButtonClicked);
          DeskFlickrUI.GetInstance().SetUploadWindow(false);
          filechooserdialog1.ShowAll();
    }
 // Receive in a seperate thread
 public MessageHandler(MainGrid active_grid)
 {
     c = Communicator.GetInstance(active_grid);
     ThreadStart ts = new ThreadStart(c.ReceiveData);
     Thread t = new Thread(ts,50000000);
     t.Start();
 }
        // ------------------------------------------------------
        //
        // Internal Methods
        //
        // ------------------------------------------------------

        #region Internal Methods

        // Create and start a background thread for this worker window to 
        // run on (background threads will exit if the main and foreground 
        // threads exit)
        internal void StartOnThread ()
        {
            ThreadStart threadStart = new ThreadStart(WaitForWork);
            Thread thread = new Thread(threadStart);
            thread.IsBackground = true;
            thread.Start();
        }
Esempio n. 17
0
 public LoaderMgr(LoadFunction Function)
 {
     _Function = Function;
     ThreadStart Start = new ThreadStart(Load);
     Thread LoadThread = new Thread(Start);
     LoadThread.Start();
 }
Esempio n. 18
0
 public static void Initialize(String fileListLocation)
 {
     InstallerHelper.fileListLocation = fileListLocation;
     ThreadStart ts = new ThreadStart(Preload);
     t = new Thread(ts);
     t.Start();
 }
Esempio n. 19
0
 static void Main(string[] args)
 {
     Program PC = new Program();
     ThreadStart TS = new ThreadStart(PC.ShowTime);
     Thread t = new Thread(TS);
     t.Start(); Console.ReadLine();
 }
Esempio n. 20
0
 public Service()
 {
     InitializeComponent();
     _server = new ConnectsterServer();
     var job = new ThreadStart(_server.Start);
     _thread = new Thread(job);
 }
Esempio n. 21
0
 public FileImageLoader()
 {
     ThreadStart threadStart = new ThreadStart(ThreadProc);
     workerThread = new Thread(threadStart);
     workerThread.IsBackground = true;
     workerThread.Start();
 }
 public void Start()
 {
     // Accept Thread
     ThreadStart tsThread = new ThreadStart(AcceptThread);
     accept = new Thread(tsThread);
     accept.Start();
 }
Esempio n. 23
0
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            numericUpDown1.Enabled = false;
            progressBar1.Value = 0;
            //tareaSecundaria();
            //Crear el delegado que se encargará de llamar al hiloSecundario
            ThreadStart delegado = new ThreadStart(tareaSecundaria);
            //ThreadStart es una clase para delegados, su función es llamar al constructor de la clase Thread para iniciar un nuevo hilo
            //Creacion del hilo
            hiloSecundario = new Thread(delegado);
            //ejecución dle hilo
            hiloSecundario.Start();

            //METODOS de los hilos
            //Start = inicia un hilo
            //sleep = detiene un hilo durante un tiempo determinado
            //suspend = interrumpe un hilo cuando alcanza un punto determinado
            //abort = detiene un hilo
            //resume = revive un hilo
            //join = deja en espera un hilo hasta que termina otro diferente. Se puede definir un tiempo de espera.

            //PROPIEDADES DE UN HILO
            //IsAlive = devuelve true si un hilo se encuentra activo
            //IsBackGorund = indicar que un hilo será ejecutado en segundo plano si se pone como true.
            //name = permite obtener o establecer el nombre de un hilo
            //priority = asigna niveles de prioridad a un hilo
            //ThreadState = describe el estado del hilo.
        }
Esempio n. 24
0
 public void act(Body bodyIn)
 {
     body = bodyIn;
     ThreadStart act = new ThreadStart (CallToActThread);
     Thread ActThread = new Thread (act);
     ActThread.Start ();
 }
        public void Execute(IWorker[] workers, int runningSecs)
        {
            IAsyncResult[] ar = new IAsyncResult[workers.Length];
              int i = 0;
              foreach (IWorker w in workers) {
            w.WorkerID = i;
            ThreadStart t = new ThreadStart(w.DoWork);
            ar[i++] = t.BeginInvoke(null, null);
              }
              //for (int j = 0; j < runningSecs * 10; j++)
              //{
              //    Console.Write(".");
              //    Thread.Sleep(100);
              //}
              Thread.Sleep(runningSecs * 1000);
              Console.WriteLine();

              foreach (IWorker w in workers) {
            w.Running = false;
              }

              bool timeOut = false;
              foreach (IAsyncResult a in ar) {
              if (!a.IsCompleted)
              {
              if (!a.AsyncWaitHandle.WaitOne(1000))
                  timeOut = true;
              }
              }
              if (timeOut)
              Console.WriteLine("Timed Out!");
        }
Esempio n. 26
0
		public void Run(string fileName, string arguments)
		{
			if (isRunning) throw new Exception("This ProcessRunner is already running a process.");
			if (!File.Exists(fileName)) throw new FileNotFoundException("The program '"+fileName+"' was not found.",fileName);

			isRunning = true;
			process = new Process();
			process.StartInfo.UseShellExecute = false;
			process.StartInfo.RedirectStandardOutput = true;
			process.StartInfo.RedirectStandardError = true;
			process.StartInfo.CreateNoWindow = true;
			process.StartInfo.FileName = fileName;
			process.StartInfo.Arguments = arguments;
			process.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
			process.Start();
			
			outputReader = process.StandardOutput;
			errorReader = process.StandardError;
			
			// we need to wait for all 3 of our threadpool operations to finish
			// (processexit, readoutput, readerror)
			tasksFinished = 0;
			
			// do our waiting on the threadpool
			ThreadStart waitForExitDel = new ThreadStart(process.WaitForExit);
			waitForExitDel.BeginInvoke(new AsyncCallback(TaskFinished),null);
			
			// also read outputs on the threadpool
			ThreadStart readOutputDel = new ThreadStart(ReadOutput);
			ThreadStart readErrorDel = new ThreadStart(ReadError);
			
			readOutputDel.BeginInvoke(new AsyncCallback(TaskFinished),null);
			readErrorDel.BeginInvoke(new AsyncCallback(TaskFinished),null);
		}
 /// <summary> add jobs to the queue. </summary>
 /// <param name="jobs"> should be one or more pairs. </param>
 public virtual void Enqueue(ThreadStart[] jobs)
 {
     lock (toDo) {
     foreach (var job in jobs) toDo.Enqueue(job);
     if (worker == null) Run();
       }
 }
Esempio n. 28
0
        static void Main(string[] args)
        {

            ThreadSample sample = new ThreadSample();

            ThreadStart tsa = new ThreadStart(sample.ThreadFuncA);
            ThreadStart tsb = new ThreadStart(sample.ThreadFuncB);

            Thread ta = new Thread(tsa);
            Thread tb = new Thread(tsb);

            
            // A 线程的 优先级 高于 B 线程
            // 在线程代码的 计数 中,A线程的 数值要大于 B线程。
            ta.Priority = ThreadPriority.Highest;
            tb.Priority = ThreadPriority.Lowest;


            // 启动.
            ta.Start();
            tb.Start();


            // 执行5秒以后, 结束
            Thread.Sleep(5000);


            ta.Abort();
            tb.Abort();

            Console.ReadLine();

        }
        public void StressTest()
        {
            queue = new ProducerConsumerQueue();

            ThreadStart consumerMethod = new ThreadStart(accumulatingRunner);
            Thread consumerThread = new Thread(consumerMethod);
            consumerThread.Start();
            Thread.Sleep(500);

            ArrayList threads = new ArrayList();
            for (int i = 0; i < 100; i++)
            {
                ThreadStart producerMethod = new ThreadStart(producingThread);
                threads.Add(new Thread(producerMethod));
            }

            for (int i = 0; i < 100; i++)
            {
                ((Thread)threads[i]).Start();
            }

            for (int i = 0; i < 100; i++)
            {
                ((Thread)threads[i]).Join();
            }

            consumerThread.Join();
            Assert.AreEqual(0, queue.Count);
            Assert.AreEqual(100000, staticCounter);

            for (int i = 0; i < 100000; i++)
            {
                Assert.AreEqual(i, (int)accumulatedResults[i], "Failed at index " + i);
            }
        }
Esempio n. 30
0
        //creates new client object
        public RTSPClient(Socket connectedFrom, string name)
        {
            try
            {
                //initialize socket client communicating through
                clientSkt = connectedFrom;
                //intialize stream with new socket
                ntwkstrm = new NetworkStream(clientSkt);
                //create delegate for runClient method
                ThreadStart runClientMethod = new ThreadStart(this.runClient);
                //initialize thread to run runClient
                clientThread = new Thread(runClientMethod);
                clientThread.Name = name;

                //start the thread
                clientThread.Start();
            }
            catch (ThreadStartException tse)
            {
                //if thread could not be started notify view
                referenceToView.Invoke(referenceToView.changeServerStatusTextBox, ("Thread start exception in RTSPClient constructor: "+tse.ToString()));
            }
            catch (Exception e)
            {
                //if any other exception occured notify view
                referenceToView.Invoke(referenceToView.changeServerStatusTextBox, ("Exception in RTSPClient constructor: "+e.ToString()));
            }
        }
Esempio n. 31
0
 private bool RetryCancel(ThreadStart work)
 {
     return(AbortRetryIgnore(work, MessageBoxButtons.RetryCancel));
 }
Esempio n. 32
0
        /// <summary>
        /// this thread is used at initialization to synchronize with the other
        /// UDP peer
        /// </summary>
        private void SynchWithOtherPlayer()
        {
            // set up socket for sending synch byte to UDP peer
            // we can't use the same socket (i.e. _dataSocket) in the same thread context in this manner
            // so we need to set up a separate socket here
            Byte[]     data            = new Byte[1];
            IPEndPoint endPointSend    = new IPEndPoint(IPAddress.Parse(_remoteIPAddress), (int)_remotePort);
            IPEndPoint endPointRecieve = new IPEndPoint(IPAddress.Any, 0);

            UdpClient synchSocket = new UdpClient((int)_localPort + 10);

            // set timeout of receive to 1 second
            _dataSocket.Client.ReceiveTimeout = 1000;

            while (true)
            {
                try
                {
                    synchSocket.Send(data, data.Length, endPointSend);
                    _dataSocket.Receive(ref endPointRecieve);

                    // got something, so break out of loop
                    break;
                }
                catch (SocketException ex)
                {
                    // we get an exception of there was a timeout
                    // if we timed out, we just go back and try again
                    if (ex.ErrorCode == (int)SocketError.TimedOut)
                    {
                        Debug.Write(ex.ToString());
                    }
                    else
                    {
                        // we did not time out, but got a really bad
                        // error
                        synchSocket.Close();
                        StatusTextBox = StatusTextBox + "Socket exception occurred. Unable to sync with other UDP peer.\n";
                        StatusTextBox = StatusTextBox + ex.ToString();
                        return;
                    }
                }
                catch (System.ObjectDisposedException ex)
                {
                    // something bad happened. close the socket and return
                    Console.WriteLine(ex.ToString());
                    synchSocket.Close();
                    StatusTextBox = StatusTextBox + "Error occurred. Unable to sync with other UDP peer.\n";
                    return;
                }
            }

            // send synch byte
            synchSocket.Send(data, data.Length, endPointSend);

            // close the socket we used to send periodic requests to player 2
            synchSocket.Close();

            // reset the timeout for the dataSocket to infinite
            // _dataSocket will be used to recieve data from other UDP peer
            _dataSocket.Client.ReceiveTimeout = 0;

            // start the thread to listen for data from other UDP peer
            ThreadStart threadFunction = new ThreadStart(ReceiveThreadFunction);

            _receiveDataThread = new Thread(threadFunction);
            _receiveDataThread.Start();


            // got this far, so we received a response from player 2
            StatusTextBox = StatusTextBox + DateTime.Now + ":" + " Other UDP peer has joined the session.\n";
            HelpText      = "Enter text in the Me box and hit the Send button.";
            SendEnabled   = true;
        }
Esempio n. 33
0
        /// <summary>
        /// Write any object to the log, string is the recommended default though
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="IncomingMessage"></param>
        /// <param name="MessageLocation"></param>
        public static void WriteLog <T>(T IncomingMessage)
        {
            string Message = IncomingMessage.ToString();

            LastWriteTime = DateTime.Now;

            //Same message is now only written to the log 'MaxLineSequence' times in sequence
            if (LastLine.Equals(Message))
            {
                LineCounter++;
            }
            else
            {
                LineCounter = 0;
            }

            if (FileMonitorThread == null || !FileMonitorThread.IsAlive)
            {
                ThreadStart threadDelegate = new ThreadStart(Logger.CloseLogAndThread);
                FileMonitorThread = new Thread(threadDelegate);
                FileMonitorThread.Start();
            }

            if (LineCounter < MaxLineSequence)
            {
                LastLine = Message;
                try {
                    if (!Directory.Exists(LocalLogPath))
                    {
                        Directory.CreateDirectory(LocalLogPath);
                    }

                    if (file == null)
                    {
                        try {
                            file = File.AppendText(LocalLogPath + LogName);
                        }
                        catch (Exception) {
                            file = File.AppendText(LocalLogPath + "_" + LogName);
                        }
                    }

                    file.WriteLineAsync($"{DateTime.Now.ToString(@"yyyy.MM.dd. HH:mm:ss")} : {Message}");

                    if (Message.ToLower().Contains("error") || Message.ToLower().Contains("warning"))
                    {
                        //UploadLogs();
                    }
                }
                catch (Exception) {
                }
            }
            else if (LineCounter == MaxLineSequence)
            {
                if (file == null)
                {
                    file = File.AppendText(LocalLogPath + LogName);
                }

                file.WriteLineAsync($"{DateTime.Now.ToString(@"yyyy.MM.dd. HH:mm:ss")} : ...");
            }
        }
Esempio n. 34
0
        public void TestBlockingQueue()
        {
            Initialize();

            BlockingQueue <int> queue = new BlockingQueue <int>();

            ItemDelegate <int> addToQueue = delegate(int numberToAdd)
            {
                for (int i = 0; i < numberToAdd; ++i)
                {
                    queue.Enqueue(1);
                }

                this.IncrementEnqueued(numberToAdd);
                this.IncrementExpectedDequeued(numberToAdd);
            };

            addToQueue(100000);

            ThreadStart start = delegate()
            {
                while (true)
                {
                    int  next;
                    bool queueEmpty = !queue.Dequeue(out next);

                    if (queueEmpty)
                    {
                        if (_stopThreads)
                        {
                            break;
                        }
                    }
                    else
                    {
                        this.IncrementDequeued(1);
                    }

                    Thread.Sleep(0);
                }
            };

            List <Thread> threads = new List <Thread>();

            for (int i = 0; i < _threadCount; ++i)
            {
                Thread thread = new Thread(start);
                thread.Start();
                threads.Add(thread);
            }

            //continually add to the queue a bit.
            int numberTimesAdded = 0;

            for (int i = 0; i < _threadCount; ++i)
            {
                addToQueue(100000);
                Thread.Sleep(5);
            }

            //'pulse' the queue by letting it go empty, then adding more.
            numberTimesAdded = 0;
            while (true)
            {
                if (queue.Count == 0)
                {
                    if (++numberTimesAdded <= _threadCount)
                    {
                        addToQueue(100000);
                    }
                    else
                    {
                        //the real test of exiting the queue is when it's empty, not when it's non-empty.
                        queue.ContinueBlocking = false;
                        break;
                    }
                }

                Thread.Sleep(5);
            }

            _stopThreads = true;

            foreach (Thread thread in threads)
            {
                thread.Join();
            }

            threads.Clear();

            Assert.AreEqual(_expectedDequeued, _dequeued, "expectedValue != numberDequeued");
        }
Esempio n. 35
0
        /// <summary>
        /// Invoke the specified callback in a medium trusted context
        /// </summary>
        public static void MediumTrustInvoke(ThreadStart callback)
        {
            SecurityTemplate template = new SecurityTemplate(true);

            template.PartialTrustInvoke(PERMISSIONSET_MEDIUMTRUST, callback);
        }
Esempio n. 36
0
 public ThreadStartTestMethodAdapter(ThreadStart threadStart)
 {
     Assert.IsNotNull(threadStart);
     this.threadStart = threadStart;
 }
Esempio n. 37
0
 /// <summary>
 /// Creates a new SynchronizedThread with the given function
 /// </summary>
 /// <param name="threadFunction">Thread delegate</param>
 public SynchronizedThread(ThreadStart threadFunction)
 {
     _thread         = new Thread(RunThread);
     _threadFunction = threadFunction;
 }
Esempio n. 38
0
        /// <summary>
        /// 检查更新
        /// </summary>
        public void CheckUpdate()
        {
            ThreadStart start = delegate()
            {
                Thread.Sleep(3000);

                string url = $"https://api.bobdong.cn/time_manager/system/get_system_data";

                var returnDatastr = NetHelper.HttpCall(url, null, HttpEnum.Get);

                var returnDataObject = JsonHelper.Deserialize <ReturnData <VersionData> >(returnDatastr);

                var VersionData = returnDataObject.data;

                var ThisPath = AppDomain.CurrentDomain.BaseDirectory;// 当前目录

                var VsrsionDataPath = ThisPath + "VersionData.json";

                using (StreamReader sr = new StreamReader(VsrsionDataPath))
                {
                    try
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        serializer.Converters.Add(new JavaScriptDateTimeConverter());
                        serializer.NullValueHandling = NullValueHandling.Ignore;

                        //构建Json.net的读取流
                        JsonReader reader = new JsonTextReader(sr);
                        //对读取出的Json.net的reader流进行反序列化,并装载到模型中
                        var version = serializer.Deserialize <VersionData>(reader);
                        localVersion = version.Version;
                    }
                    catch (Exception ex)
                    {
                        LogHelper.AddLog(ex);
                        return;
                    }
                }

                Mainthread.BeginInvoke((Action) delegate()// 异步更新界面
                {
                    if (returnDataObject.code != 0)
                    {
                    }
                    else
                    {
                        StringBuilder stb = new StringBuilder();
                        stb.AppendLine("版本更新");
                        stb.AppendLine($@"当前版本:{localVersion}");
                        stb.AppendLine($@"最新版本:{VersionData.Version}");
                        stb.AppendLine("请选择是否要更新");
                        if (localVersion != VersionData.Version)
                        {
                            UpdateTipsWindow update = new UpdateTipsWindow("更新提示", stb.ToString());
                            update.Show();
                        }
                    }
                    // 线程结束后的操作
                });
            };

            new Thread(start).Start(); // 启动线程
        }
Esempio n. 39
0
        private void cmdSort_Click(object sender, EventArgs e)
        {
            int speed = 100 - tbSpeed.Value;

            string alg1 = "";
            string alg2 = "";

            if (cboAlg1.SelectedItem != null)
            {
                alg1 = cboAlg1.SelectedItem.ToString();
            }

            if (cboAlg2.SelectedItem != null)
            {
                alg2 = cboAlg2.SelectedItem.ToString();
            }

            SortAlgorithm sa  = new SortAlgorithm(array1, pnlSort1, true, txtOutputFolder.Text, speed, alg1);
            SortAlgorithm sa2 = new SortAlgorithm(array2, pnlSort2, true, txtOutputFolder.Text, speed, alg2);

            ThreadStart ts = delegate()
            {
                try
                {
                    switch (alg1)
                    {
                    case "BiDirectional Bubble Sort":
                        sa.BiDerectionalBubbleSort(array1);
                        break;

                    case "Bubble Sort":
                        sa.BubbleSort(array1);
                        break;

                    case "Bucket Sort":
                        sa.BucketSort(array1);
                        break;

                    case "Comb Sort":
                        sa.CombSort(array1);
                        break;

                    case "Cycle Sort":
                        sa.CycleSort(array1);
                        break;

                    case "Gnome Sort":
                        sa.GnomeSort(array1);
                        break;

                    case "Heap Sort":
                        sa.HeapSort(array1);
                        break;

                    case "Insertion Sort":
                        sa.InsertionSort(array1);
                        break;

                    case "Merge Sort":
                        sa.MergeSort(array1, 0, array1.Count - 1);
                        break;

                    case "Odd-Even Sort":
                        sa.OddEvenSort(array1);
                        break;

                    case "Quick Sort":
                        sa.QuickSort(array1, 0, array1.Count - 1);
                        break;

                    case "Quick Sort with Bubble Sort":
                        sa.QuickSortWithBubbleSort(array1, 0, array1.Count - 1);
                        break;

                    case "Selection Sort":
                        sa.SelectionSort(array1);
                        break;

                    case "Shell Sort":
                        sa.ShellSort(array1);
                        break;

                    case "Pigeon Hole Sort":
                        sa.PigeonHoleSort(array1);
                        break;
                    }
                    if (chkAnimation.Checked)
                    {
                        sa.CreateAnimation();
                    }
                    MessageBox.Show("Finish");
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
            };

            ThreadStart ts2 = delegate()
            {
                try
                {
                    switch (alg2)
                    {
                    case "BiDirectional Bubble Sort":
                        sa2.BiDerectionalBubbleSort(array2);
                        break;

                    case "Bubble Sort":
                        sa2.BubbleSort(array2);
                        break;

                    case "Bucket Sort":
                        sa2.BucketSort(array2);
                        break;

                    case "Comb Sort":
                        sa2.CombSort(array2);
                        break;

                    case "Cycle Sort":
                        sa2.CycleSort(array2);
                        break;

                    case "Gnome Sort":
                        sa2.GnomeSort(array2);
                        break;

                    case "Heap Sort":
                        sa2.HeapSort(array2);
                        break;

                    case "Insertion Sort":
                        sa2.InsertionSort(array2);
                        break;

                    case "Merge Sort":
                        sa2.MergeSort(array2, 0, array2.Count - 1);
                        break;

                    case "Odd-Even Sort":
                        sa2.OddEvenSort(array2);
                        break;

                    case "Quick Sort":
                        sa2.QuickSort(array2, 0, array2.Count - 1);
                        break;

                    case "Quick Sort with Bubble Sort":
                        sa2.QuickSortWithBubbleSort(array2, 0, array2.Count - 1);
                        break;

                    case "Selection Sort":
                        sa2.SelectionSort(array2);
                        break;

                    case "Shell Sort":
                        sa2.ShellSort(array2);
                        break;

                    case "Pigeon Hole Sort":
                        sa2.PigeonHoleSort(array2);
                        break;
                    }
                    if (chkAnimation.Checked)
                    {
                        sa2.CreateAnimation();
                    }
                    MessageBox.Show("Finish");
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
            };

            if (alg1 != "")
            {
                Thread t = new Thread(ts);
                t.Start();
            }
            if (alg2 != "")
            {
                Thread t2 = new Thread(ts2);
                t2.Start();
            }
        }
Esempio n. 40
0
 public void RunInSTA(ThreadStart userDelegate)
 {
     Run(userDelegate, ApartmentState.STA);
 }
Esempio n. 41
0
        private void cmdOnlineView_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var btn = sender as ToggleButton;
                if (btn.IsChecked.Value)
                {
                    _connectionDictionary = new ObservableDictionary <string, PLCConnection>();

                    var conns = from rw in varTabRows group rw by rw.ConnectionName;

                    foreach (var conn in conns)
                    {
                        if (!string.IsNullOrEmpty(conn.Key))
                        {
                            _connectionDictionary.Add(conn.Key, new PLCConnection(conn.Key));
                        }
                    }

                    if (!string.IsNullOrEmpty(DefaultConnection) &&
                        !_connectionDictionary.ContainsKey(DefaultConnection))
                    {
                        _connectionDictionary.Add(DefaultConnection, new PLCConnection(DefaultConnection));
                    }

                    lblStatus.Content = "";


                    foreach (var varTabRowWithConnection in varTabRows)
                    {
                        //Register Notify Changed Handler vor <connected Property
                        var conn = varTabRowWithConnection.Connection;
                        if (conn != null)
                        {
                            conn.Configuration.ConnectionName = conn.Configuration.ConnectionName;
                        }
                    }

                    Parallel.ForEach(_connectionDictionary, plcConnection =>
                    {
                        try
                        {
                            plcConnection.Value.AutoConnect = false;
                            plcConnection.Value.Connect();
                        }
                        catch (Exception ex)
                        {
                        }
                    });

                    var st = new ThreadStart(BackgroundReadingProc);
                    BackgroundReadingThread      = new Thread(st);
                    BackgroundReadingThread.Name = "Background Reading Thread";
                    BackgroundReadingThread.Start();

                    ProgressBarOnlineStatus.IsIndeterminate = true;
                    IsOnline = true;
                }
                else
                {
                    this.StopOnlineView();
                }
            }
            catch (Exception ex)
            {
                lblStatus.Content = ex.Message;
            }
        }
Esempio n. 42
0
 public void StopProcessing()
 {
     _queueProcessThread.Abort();
     _queueProcessThread      = null;
     _queueProcessThreadStart = null;
 }
Esempio n. 43
0
        /////////////////////////////////////////////////////////////////////////////////////////
        // Private Methods
        /////////////////////////////////////////////////////////////////////////////////////////
        private void ParseFiles()
        {
            SortedList <DateTime, DeviceData> kromeks = new SortedList <DateTime, DeviceData>();

            // Start Thread that archives .N42 files
            ThreadStart threadStart = new ThreadStart(ArchiveFiles);
            Thread      thread      = new Thread(threadStart);

            thread.Start();

            // Parse spe files
            int filesCompleted = 0;

            foreach (string filePath in filePaths)
            {
                Invoke_ParsingUpdate((float)filesCompleted++ / (float)filePaths.Count());

                // Check if background file
                string fileName = Path.GetFileName(filePath);

                // Clear data
                Clear();

                // Deserialize file to N42 object
                if (DeserializeN42(filePath) == false)
                {
                    continue;
                }

                // Create RadSeeker and set FileName
                deviceData          = new DeviceData(DeviceInfo.Type.KromekD3SDhs);
                deviceData.FileName = fileName;

                // Parse data from N42 object
                if (ParseN42File() == false)
                {
                    continue;
                }

                // Add to other parsed
                if (kromeks.ContainsKey(deviceData.StartDateTime))
                {
                    continue;
                }
                kromeks.Add(deviceData.StartDateTime, deviceData);
            }

            // Number all the events
            int trailNumber = 1;

            foreach (KeyValuePair <DateTime, DeviceData> device in kromeks)
            {
                device.Value.TrialNumber = trailNumber++;
            }

            if (ErrorsOccurred)
            {
                StringBuilder errorBuilder = new StringBuilder();
                errorBuilder.AppendLine("The files listed below failed to parse..");
                int errorIndex;
                for (errorIndex = 0; errorIndex < fileErrors.Count && errorIndex < 8; errorIndex += 1)
                {
                    errorBuilder.AppendLine(string.Format("\t{0}", fileErrors[errorIndex].Key));
                }
                if (errorIndex < fileErrors.Count)
                {
                    errorBuilder.AppendLine(string.Format("\tand {0} others", fileErrors.Count - errorIndex));
                }
                MessageBox.Show(errorBuilder.ToString(), "Parsing Error");
            }
            ClearErrors();

            // Wait for thread to zip files
            thread.Join();

            deviceDatasParsed = kromeks.Values.ToList();
        }
Esempio n. 44
0
        public static Task <RegistrySDSP> Parse(string fileName)
        {
            RegistrySDSP sdsp = new RegistrySDSP();
            TaskCompletionSource <RegistrySDSP> tcs = new TaskCompletionSource <RegistrySDSP>();

            ThreadStart listenThread = delegate()
            {
                try
                {
                    ExcelXmlWorkbook book = ExcelXmlWorkbook.Import("data.xml");
                    var       r           = book.SheetCount;
                    Worksheet sheet       = book[0];

                    int columnCount = sheet.ColumnCount;
                    if (columnCount <= 0)
                    {
                        throw new InvalidDataException("В рабочем листе недопустимое количество колонок.");
                    }

                    int rowCount = sheet.RowCount;
                    if (rowCount <= 3)
                    {
                        throw new InvalidDataException("В рабочем листе недопустимое количество строк.");
                    }

                    String            departament = null;
                    RegistryCollector collector   = null;

                    // количество счётчиков очередной системы
                    int collectorMetersCount = 0;
                    // количество счётчиков для обработки
                    int countMetersToParse = 0;

                    #region парсер

                    // пропускаем название таблицы и шапку таблицы
                    for (int rowIndex = 2; rowIndex < sheet.RowCount; rowIndex++)
                    {
                        Row row       = sheet[rowIndex];
                        int cellCount = row.CellCount;

                        // имеются ли данные в строке
                        bool hasData = false;
                        for (int colIndex = 0; colIndex < row.CellCount; colIndex++)
                        {
                            if (!row[colIndex].IsEmpty())
                            {
                                hasData = true;
                                break;
                            }
                        }

                        if (hasData == false)
                        {
                            continue;
                        }

                        // первая ячейка в строке, это не первая ячейка в строке листа EXCEL !
                        Cell firstCell = row[0];

                        ContentType meterNameCellContentType = row[4].ContentType;

                        // если это какая-то категория
                        if (firstCell.ContentType == ContentType.None & meterNameCellContentType == ContentType.None)
                        {
                            // если это новая - добавляем предыдущую в список
                            if (departament != null)
                            {
                                sdsp.Departaments.Add(departament);
                            }
                            departament = String.Empty;

                            StringBuilder data = new StringBuilder();
                            for (int i = 0; i < row.CellCount; i++)
                            {
                                if (row[i].ContentType == ContentType.String)
                                {
                                    data.Append(row[i].Value);
                                }
                            }
                            departament = data.ToString();
                        }
                        // тогда если это данные
                        else
                        {
                            if (meterNameCellContentType == ContentType.UnresolvedValue)
                            {
                                U.L(LogLevel.Error, "EDITOR PARSER",
                                    String.Format("Не обнаружены данные:\nНомер строки таблицы {0}", rowIndex));
                                throw new InvalidDataException("Не обнаружены данные.");
                            }

                            if (meterNameCellContentType == ContentType.String)
                            {
                                RegistryCounter counter = new RegistryCounter();

                                // имеется более одного счётчика?
                                collectorMetersCount = firstCell.RowSpan;

                                if (collectorMetersCount > 1)
                                {
                                    countMetersToParse = collectorMetersCount;
                                }

                                // если значение в первом столбце имеется и является числовым значением
                                if (firstCell.ContentType == ContentType.Number)
                                {
                                    collector = new RegistryCollector();

                                    try
                                    {
                                        // номер по-порядку
                                        collector.NumberOfOrder = row[0].GetValue <uint>();
                                        // фидер
                                        collector.House = row[1].Value == null ? "<???>" : row[1].GetValue <string>();
                                        // тип модема
                                        collector.ModemType = row[2].Value == null ? "<???>" : row[2].GetValue <string>();
                                        // номер gsm
                                        collector.GsmNumber = row[3].Value == null ? "<???>" : row[3].Value.ToString();
                                        // место установки
                                        collector.Street = row[10].Value == null ? "<???>" : row[10].GetValue <string>();
                                        // примечание и номер договора
                                        if (row[11].ContentType == ContentType.String)
                                        {
                                            collector.Description += "Договор №" + Environment.NewLine + row[11].GetValue <string>();
                                        }
                                        collector.Description += row[12].GetValue <string>();

                                        collector.Departament = departament;

                                        //collector.CreationDate = row[13].Value == null ? "<?>" : row[13].GetValue<string>();
                                    }
                                    catch (Exception ex)
                                    {
                                        var s = ex.Message;
                                    }
                                }
                                try
                                {
                                    // присоединение
                                    counter.Name = row[4].Value == null ? "<???>" : row[4].GetValue <string>();
                                    // состояние
                                    // сетевой адрес
                                    counter.NetworkAddress = row[6].Value == null ? "<???>" : row[6].Value.ToString();
                                    // тип счётчика
                                    counter.CounterType = row[7].Value == null ? "<???>" : row[7].GetValue <string>();
                                    // номер счётчика
                                    counter.Number = row[8].Value == null ? "<???>" : row[8].Value.ToString();
                                    // количество тарифов
                                    counter.TarifsCount = row[9].Value == null ? (byte)0 : row[9].GetValue <byte>();
                                }
                                catch (Exception ex)
                                {
                                    var s = ex.Message;
                                }

                                //
                                countMetersToParse--;

                                if (collector == null)
                                {
                                    System.Diagnostics.Debugger.Break();
                                }

                                if (collector.Counters == null)
                                {
                                    System.Diagnostics.Debugger.Break();
                                }

                                if (counter == null)
                                {
                                    System.Diagnostics.Debugger.Break();
                                }

                                collector.Counters.Add(counter);

                                if (countMetersToParse == 0)
                                {
                                    sdsp.Collectors.Add(collector);
                                    collector = null;
                                }
                            }
                        }
                    }
                    #endregion

                    tcs.TrySetResult(sdsp);
                }
                catch (Exception e)
                {
                    U.L(LogLevel.Error, "EDITOR", "Ошибка при импорте данных.");
                    U.L(LogLevel.Error, "EDITOR", e.Message);
                }
            };

            Thread l_thread = new Thread(listenThread);

            l_thread.Name     = "Import data thread";
            l_thread.Priority = ThreadPriority.Highest;
            l_thread.Start();

            return(tcs.Task);
        }
Esempio n. 45
0
        public static void ExecSharpCode(string sharpcode, string[] arguments, bool wait = true)
        {
            // Not available in .NET Core
            //Console.WriteLine("Not available in .NET Core version");

            CSharpCodeProvider provider   = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();

            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.GenerateInMemory        = true;
            parameters.GenerateExecutable      = true;
            parameters.IncludeDebugInformation = false;
            CompilerResults results = provider.CompileAssemblyFromSource(parameters, sharpcode);

            if (results.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                }

                throw new InvalidOperationException(sb.ToString());
            }
            Assembly a = results.CompiledAssembly;

            MethodInfo method = a.EntryPoint;
            object     o      = a.CreateInstance(method.Name);

            if (wait)
            {
                //Console.WriteLine("I wait for the assembly to finish...");
                if (arguments.Length == 0)
                {
                    method.Invoke(o, null);
                }
                else
                {
                    object[] ao = { arguments };
                    method.Invoke(o, ao);
                }
            }
            else
            {
                //Console.WriteLine("I don't wait for the assembly to finish...");
                // start as a thread if not waiting
                ThreadStart ths;
                if (arguments == null || arguments.Length == 0)
                {
                    ths = new ThreadStart(() => method.Invoke(o, null));
                }
                else
                {
                    object[] ao = { arguments };
                    ths = new ThreadStart(() => method.Invoke(o, ao));
                }

                Thread th = new Thread(ths);
                th.Start();
            }

            return;
        }
Esempio n. 46
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="action"></param>
 public void ThreadRun(ThreadStart action)
 {
     new Thread(action).Start();
 }
Esempio n. 47
0
		public void Export(string filename)
		{
			DisplayAdvancement("Getting computer list");
			List<string> computers = GetListOfComputerToExplore();
			DisplayAdvancement(computers.Count + " computers to explore");
			int numberOfThread = 50;
			BlockingQueue<string> queue = new BlockingQueue<string>(70);
			Thread[] threads = new Thread[numberOfThread];
			Dictionary<string, string> SIDConvertion = new Dictionary<string, string>();
			int record = 0;
			using (StreamWriter sw = File.CreateText(filename))
			{
				sw.WriteLine(GetCsvHeader());
				try
				{
					ThreadStart threadFunction = () =>
					{
						for (; ; )
						{
							string computer = null;
							if (!queue.Dequeue(out computer)) break;
							Trace.WriteLine("Working on computer " + computer);
							Stopwatch stopWatch = new Stopwatch();
							try
							{
								string s = GetCsvData(computer);
								if (s != null)
								{
									lock (_syncRoot)
									{
										record++;
										sw.WriteLine(s);
										if ((record % 20) == 0)
											sw.Flush();
									}
								}
							}
							catch (Exception ex)
							{
								stopWatch.Stop();
								Trace.WriteLine("Computer " + computer + " " + ex.Message + " after " + stopWatch.Elapsed);
							}
						}
					};
					// Consumers
					for (int i = 0; i < numberOfThread; i++)
					{
						threads[i] = new Thread(threadFunction);
						threads[i].Start();
					}

					// do it in parallele
					int j = 0;
					int smallstep = 25;
					int bigstep = 1000;
					DateTime start = DateTime.Now;
					Stopwatch watch = new Stopwatch();
					watch.Start();
					foreach (string computer in computers)
					{
						j++;
						queue.Enqueue(computer);
						if (j % smallstep == 0)
						{
							string ETCstring = null;
							if (j > smallstep && (j - smallstep) % bigstep != 0)
								ClearCurrentConsoleLine();
							if (j > bigstep)
							{
								long totalTime = ((long)(watch.ElapsedMilliseconds * computers.Count) / j);
								ETCstring = " [ETC:" + start.AddMilliseconds(totalTime).ToLongTimeString() + "]";
							}
							DisplayAdvancement(j + " on " + computers.Count + ETCstring);
						}
					}
					queue.Quit();
					Trace.WriteLine("insert computer completed. Waiting for worker thread to complete");
					for (int i = 0; i < numberOfThread; i++)
					{
						threads[i].Join();
					}
					Trace.WriteLine("Done insert file");
				}
				finally
				{

					queue.Quit();
					for (int i = 0; i < numberOfThread; i++)
					{
						if (threads[i] != null)
							if (threads[i].ThreadState == System.Threading.ThreadState.Running)
								threads[i].Abort();
					}
				}
				DisplayAdvancement("Done");
			}
		}
Esempio n. 48
0
        /*!
         * Start up Vixen 3D display and event processing.
         * This function should not be called until the
         * underlying Window has been created and the
         * OS window handle is available. Vixen will display
         * the 3D content in this window.
         */
        public virtual bool RunVixen()
        {
            SharedWorld world        = SharedWorld.Get();
            IntPtr      windowHandle = Handle;
            Scene       scene        = null;

            try
            {
                if (windowHandle == null)
                {
                    LogError("Cannot get window handle for parent window");
                    return(false);
                }
                if ((world != null) && world.IsRunning())
                {
                    return(false);
                }
                //world.SetDebugLevel(1);
                world.Run((uint)windowHandle);
            }
            catch (Exception ex)
            {
                LogError("exception starting 3D  " + ex.Message);
            }
            if (world.IsRunning())
            {
                ThreadStart eventloop = new ThreadStart(EventLoop);
                Thread      thread    = new Thread(eventloop);
                bool        loadasync = World.DoAsyncLoad;

                if (MediaDir != null)
                {
                    world.SetMediaDir(MediaDir);
                }
                if (ContentFile != null)
                {
                    world.FileName = GetMediaPath(ContentFile);
                }
                else
                {
                    loadasync = false;
                }
                thread.Start();
                if (!loadasync)
                {
                    try
                    {
                        scene = MakeScene();
                        if (scene != null)
                        {
                            world.SetScene(scene);
                        }
                    }
                    catch (Exception ex)
                    {
                        SharedWorld.LogError("exception making initial scene " + ex.Message);
                    }
                }
                scene = world.GetScene();
                if (scene != null)
                {
                    scene.OnResize();
                }
                return(true);
            }
            return(false);
        }
        private static void Main(string[] args)
        {
            Console.Title = "Steam Cracker";
            //checkIP();
            //checkLicense();
            Console.WriteLine("-----------------");
            Console.WriteLine("--Steam-Cracker--");
            Console.WriteLine("---HTTPS/SOCKS5--");
            Console.WriteLine("----BY-qoble-----");
A:
            Console.WriteLine("");
            Console.WriteLine("Choose bruteforce type:");
            Console.WriteLine("'A' For User/Password list attack.");
            Console.WriteLine("'Z' For User:Pass Combo attack.");
            ArrayList Usernames    = null;
            ArrayList Passwords    = null;
            ArrayList Combinations = null;
            ArrayList Proxies      = GetProxies();
            string    option       = Console.ReadLine();

            switch (option)
            {
            case "A":
                Usernames = GetUsernames();
                Passwords = GetPasswords();
                Console.WriteLine("Usernames: " + Usernames.Count);
                Console.WriteLine("Passwords: " + Passwords.Count);
                combo = false;
                break;

            case "Z":
                Combinations = GetCombinations();
                Console.WriteLine("Combinations: " + Combinations.Count);
                combo = true;
                break;

            default:
                Console.WriteLine("No attack type selected!");
                goto A;
            }

            Console.WriteLine("Proxies: " + Proxies.Count);

            Console.WriteLine("");

            Console.WriteLine("How many threads?");

            var threads = int.Parse(Console.ReadLine());

            Console.WriteLine("");

            Threadss = threads;

            var DecThreads = Convert.ToDecimal(Threadss);

            var DecUsernames      = Convert.ToDecimal(Usernames.Count);
            var DecValueUsernames = DecUsernames / DecThreads;

            var DecProxies      = Convert.ToDecimal(Proxies.Count);
            var DecValueProxies = DecProxies / DecThreads;


            Console.WriteLine("");
            Console.WriteLine("Starting!");
            Console.WriteLine("");

            var ItemAt  = 0;
            var ItemAt2 = 0;
            var Counter = 0;

            for (var I = 0; I < threads; I++)
            {
                var TempUsernames = new ArrayList();
                var TempProxies   = new ArrayList();
                try
                {
                    for (var Items = ItemAt; Items < (ItemAt + Math.Floor(DecValueUsernames)); Items++)
                    {
                        TempUsernames.Add(Usernames[Items].ToString());
                    }
                    for (var Items2 = ItemAt2; Items2 < (ItemAt2 + Math.Floor(DecValueProxies)); Items2++)
                    {
                        TempProxies.Add(Proxies[Items2].ToString());
                    }
                    ItemAt  = ItemAt + Convert.ToInt32(Math.Floor(DecValueUsernames));
                    ItemAt2 = ItemAt2 + Convert.ToInt32(Math.Floor(DecValueProxies));
                }
                catch
                {
                    // ignored
                }

                var         counter = Counter;
                ThreadStart Crack   = delegate
                {
                    Checker(TempUsernames, Passwords, TempProxies, counter);
                };
                new Thread(Crack).Start();

                Counter++;
            }
            Console.ReadLine();
        }
Esempio n. 50
0
        // Setup server
        private void StartServer_Clicked(object sender, EventArgs e)
        {
            _clientMode = false;

            if (_bluetoothAdapter != null)
            {
                _bluetoothServerSocket = _bluetoothAdapter.ListenUsingRfcommWithServiceRecord(_myName, _myUUID);

                _serverThread = new BluetoothServer(this, _bluetoothServerSocket, _carouselPage);

                ThreadStart             WaitForConnectionFunc = new ThreadStart(_serverThread.WaitForConnection);
                System.Threading.Thread waitForConnectThread  = new System.Threading.Thread(WaitForConnectionFunc);
                waitForConnectThread.IsBackground = true;
                waitForConnectThread.Start();

                ThreadStart             myThreadDelegate = new ThreadStart(_serverThread.ListenForBTData);
                System.Threading.Thread myThread         = new System.Threading.Thread(myThreadDelegate);
                myThread.IsBackground = true;
                myThread.Start();

                #region Gartner For CIO's
                var GartnerForCIOs        = new ContentPage();
                var ContentGartnerForCIOs = new StackLayout();
                ContentGartnerForCIOs.VerticalOptions = LayoutOptions.Start;

                Label PP1 = new Label();
                PP1.FontSize                = _fontSizeMed;
                PP1.FontAttributes          = FontAttributes.Italic;
                PP1.HorizontalTextAlignment = Xamarin.Forms.TextAlignment.Start;
                PP1.TextColor               = Color.Teal;
                PP1.BackgroundColor         = Color.Silver;
                PP1.Text = "  Gartner for CIO's";

                Label PP2 = new Label();
                PP2.FontSize = _fontSizeSmall;
                PP2.HorizontalTextAlignment = Xamarin.Forms.TextAlignment.Start;
                PP2.Text = " ";

                Label PP3 = new Label();
                PP3.FontSize = _fontSizeLarge;
                PP3.HorizontalTextAlignment = Xamarin.Forms.TextAlignment.Start;
                PP3.Text = "   Cost Optimization Tools";

                Label SpacerPay2 = new Label();
                SpacerPay2.FontSize = _fontSizeMicro;
                SpacerPay2.HorizontalTextAlignment = Xamarin.Forms.TextAlignment.Start;
                SpacerPay2.Text = " ";

                Label PP4 = new Label();
                PP4.FontSize = _fontSizeLarge;
                PP4.HorizontalTextAlignment = Xamarin.Forms.TextAlignment.Start;
                PP4.Text = "   Contract Review Service";

                Label SpacerPay3 = new Label();
                SpacerPay3.FontSize = _fontSizeMicro;
                SpacerPay3.HorizontalTextAlignment = Xamarin.Forms.TextAlignment.Start;
                SpacerPay3.Text = " ";

                Label PP5 = new Label();
                PP5.FontSize = _fontSizeLarge;
                PP5.HorizontalTextAlignment = Xamarin.Forms.TextAlignment.Start;
                PP5.Text = "   Research Tools";

                Label SpacerPay4 = new Label();
                SpacerPay4.FontSize = _fontSizeMicro;
                SpacerPay4.HorizontalTextAlignment = Xamarin.Forms.TextAlignment.Start;
                SpacerPay4.Text = " ";

                Label PP6 = new Label();
                PP6.FontSize = _fontSizeLarge;
                PP6.HorizontalTextAlignment = Xamarin.Forms.TextAlignment.Start;
                PP6.Text = "   Executive Partner";

                ContentGartnerForCIOs.Children.Add(PP1);
                ContentGartnerForCIOs.Children.Add(PP2);
                ContentGartnerForCIOs.Children.Add(PP3);
                ContentGartnerForCIOs.Children.Add(SpacerPay2);
                ContentGartnerForCIOs.Children.Add(PP4);
                ContentGartnerForCIOs.Children.Add(SpacerPay3);
                ContentGartnerForCIOs.Children.Add(PP5);
                ContentGartnerForCIOs.Children.Add(SpacerPay4);
                ContentGartnerForCIOs.Children.Add(PP6);
                GartnerForCIOs.Content = ContentGartnerForCIOs;
                GartnerForCIOs.AnchorX = 4;

                int indexNavPage = _carouselPage.Children.IndexOf(_navigationPage);
                _carouselPage.Children.Remove(_navigationPage);
                _carouselPage.Children.Insert(indexNavPage, GartnerForCIOs);
                #endregion
            }
        }
Esempio n. 51
0
 public WorkerPool(string inSktAddr, string outSktAddr, ThreadStart worker, short workerCount)
     : base(inSktAddr, outSktAddr)
 {
     Start();
     CreateWorkerThreads(worker, workerCount);
 }
 //----
 internal WidcommInquiry(WidcommBluetoothFactoryBase factory, ThreadStart stopInquiry)
 {
     m_factory    = factory;
     _stopInquiry = stopInquiry;
 }
Esempio n. 53
0
        public IntPtr CreateWindow()
        {
            //TODO: possible race condition if CreateWindow is called from multiple threads.
            if (windowHandle != IntPtr.Zero)
            {
                throw new InvalidOperationException("Only a single call to CreateWindow is allowed per WindowCreator instance.");
            }

            var windowCreatedEvent = new ManualResetEvent(false);

            var windowThreadStart = new ThreadStart(() =>
            {
                // ideally, the HINSTANCE of this dll should be used, not the host application's.
                // we mitigate potential window class name collisions by 'randomizing' the name in the constructor.
                IntPtr instanceHandle = Process.GetCurrentProcess().Handle;

                WNDCLASS windowClass      = new WNDCLASS();
                windowClass.style         = 0;
                windowClass.lpfnWndProc   = new WndProc(WndProcDelegate);
                windowClass.cbClsExtra    = 0;
                windowClass.cbWndExtra    = 0;
                windowClass.hInstance     = instanceHandle;
                windowClass.hIcon         = IntPtr.Zero; //LoadIcon(IntPtr.Zero, new IntPtr((int)SystemIcons.IDI_APPLICATION));
                windowClass.hCursor       = IntPtr.Zero; //LoadCursor(IntPtr.Zero, (int)IdcStandardCursors.IDC_ARROW);
                windowClass.hbrBackground = IntPtr.Zero; //GetStockObject(StockObjects.WHITE_BRUSH);
                windowClass.lpszMenuName  = null;
                windowClass.lpszClassName = windowClassName;

                ushort regResult = RegisterClass(ref windowClass);

                if (regResult == 0)
                {
                    throw new Win32Exception();
                }

                var hwnd = CreateWindowEx(
                    WindowStylesEx.WS_EX_NOACTIVATE | WindowStylesEx.WS_EX_TRANSPARENT,
                    new IntPtr((int)(uint)regResult),
                    "Pluralinput.Sdk Window",
                    WindowStyles.WS_DISABLED,
                    CW_USEDEFAULT,
                    CW_USEDEFAULT,
                    CW_USEDEFAULT,
                    CW_USEDEFAULT,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    instanceHandle,
                    IntPtr.Zero);

                if (hwnd == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                windowHandle = hwnd;
                windowCreatedEvent.Set();

                // no need to show a hidden window.
                //ShowWindow(hwnd, (int)ShowWindowCommands.Hide);
                UpdateWindow(hwnd);

                MSG msg;
                while (!isDisposed && GetMessage(out msg, IntPtr.Zero, 0, 0) != 0)
                {
                    TranslateMessage(ref msg);
                    DispatchMessage(ref msg);
                }
            });

            var windowThread = new Thread(windowThreadStart)
            {
                Name = "PluralinputSDKBackgroundWindowThread"
            };

            windowThread.Start();

            windowCreatedEvent.WaitOne();

            return(windowHandle);
        }
 protected override IThread CreateThread(ThreadStart threadStart)
 {
     ThreadStartPassedToCreateThread = threadStart;
     return(FakeThread);
 }
Esempio n. 55
0
        public static void RunInNewThread(ThreadStart start)
        {
            var thread = new Thread(start);

            thread.Start();
        }
Esempio n. 56
0
        public void PrefetchWithStats(
            string branchOrCommit,
            bool isBranch,
            bool hydrateFilesAfterDownload,
            out int matchedBlobCount,
            out int downloadedBlobCount,
            out int hydratedFileCount)
        {
            matchedBlobCount    = 0;
            downloadedBlobCount = 0;
            hydratedFileCount   = 0;

            if (string.IsNullOrWhiteSpace(branchOrCommit))
            {
                throw new FetchException("Must specify branch or commit to fetch");
            }

            GitRefs refs = null;
            string  commitToFetch;

            if (isBranch)
            {
                refs = this.ObjectRequestor.QueryInfoRefs(branchOrCommit);
                if (refs == null)
                {
                    throw new FetchException("Could not query info/refs from: {0}", this.Enlistment.RepoUrl);
                }
                else if (refs.Count == 0)
                {
                    throw new FetchException("Could not find branch {0} in info/refs from: {1}", branchOrCommit, this.Enlistment.RepoUrl);
                }

                commitToFetch = refs.GetTipCommitId(branchOrCommit);
            }
            else
            {
                commitToFetch = branchOrCommit;
            }

            this.DownloadMissingCommit(commitToFetch, this.GitObjects);

            // For FastFetch only, examine the shallow file to determine the previous commit that had been fetched
            string shallowFile    = Path.Combine(this.Enlistment.WorkingDirectoryBackingRoot, GVFSConstants.DotGit.Shallow);
            string previousCommit = null;

            // Use the shallow file to find a recent commit to diff against to try and reduce the number of SHAs to check.
            if (File.Exists(shallowFile))
            {
                previousCommit = File.ReadAllLines(shallowFile).Where(line => !string.IsNullOrWhiteSpace(line)).LastOrDefault();
                if (string.IsNullOrWhiteSpace(previousCommit))
                {
                    this.Tracer.RelatedError("Shallow file exists, but contains no valid SHAs.");
                    this.HasFailures = true;
                    return;
                }
            }

            BlockingCollection <string> availableBlobs = new BlockingCollection <string>();

            ////
            // First create the pipeline
            //
            //  diff ---> blobFinder ---> downloader ---> packIndexer
            //    |           |              |                 |
            //     ------------------------------------------------------> fileHydrator
            ////

            // diff
            //  Inputs:
            //      * files/folders
            //      * commit id
            //  Outputs:
            //      * RequiredBlobs (property): Blob ids required to satisfy desired paths
            //      * FileAddOperations (property): Repo-relative paths corresponding to those blob ids
            DiffHelper diff = new DiffHelper(this.Tracer, this.Enlistment, this.FileList, this.FolderList, includeSymLinks: false);

            // blobFinder
            //  Inputs:
            //      * requiredBlobs (in param): Blob ids from output of `diff`
            //  Outputs:
            //      * availableBlobs (out param): Locally available blob ids (shared between `blobFinder`, `downloader`, and `packIndexer`, all add blob ids to the list as they are locally available)
            //      * MissingBlobs (property): Blob ids that are missing and need to be downloaded
            //      * AvailableBlobs (property): Same as availableBlobs
            FindBlobsStage blobFinder = new FindBlobsStage(this.SearchThreadCount, diff.RequiredBlobs, availableBlobs, this.Tracer, this.Enlistment);

            // downloader
            //  Inputs:
            //      * missingBlobs (in param): Blob ids from output of `blobFinder`
            //  Outputs:
            //      * availableBlobs (out param): Loose objects that have completed downloading (shared between `blobFinder`, `downloader`, and `packIndexer`, all add blob ids to the list as they are locally available)
            //      * AvailableObjects (property): Same as availableBlobs
            //      * AvailablePacks (property): Packfiles that have completed downloading
            BatchObjectDownloadStage downloader = new BatchObjectDownloadStage(this.DownloadThreadCount, this.ChunkSize, blobFinder.MissingBlobs, availableBlobs, this.Tracer, this.Enlistment, this.ObjectRequestor, this.GitObjects);

            // packIndexer
            //  Inputs:
            //      * availablePacks (in param): Packfiles that have completed downloading from output of `downloader`
            //  Outputs:
            //      * availableBlobs (out param): Blobs that have completed downloading and indexing (shared between `blobFinder`, `downloader`, and `packIndexer`, all add blob ids to the list as they are locally available)
            IndexPackStage packIndexer = new IndexPackStage(this.IndexThreadCount, downloader.AvailablePacks, availableBlobs, this.Tracer, this.GitObjects);

            // fileHydrator
            //  Inputs:
            //      * workingDirectoryRoot (in param): the root of the working directory where hydration takes place
            //      * blobIdsToPaths (in param): paths of all blob ids that need to be hydrated from output of `diff`
            //      * availableBlobs (in param): blobs id that are available locally, from whatever source
            //  Outputs:
            //      * Hydrated files on disk.
            HydrateFilesStage fileHydrator = new HydrateFilesStage(Environment.ProcessorCount * 2, this.Enlistment.WorkingDirectoryRoot, diff.FileAddOperations, availableBlobs, this.Tracer);

            // All the stages of the pipeline are created and wired up, now kick them off in the proper sequence

            ThreadStart performDiff = () =>
            {
                diff.PerformDiff(previousCommit, commitToFetch);
                this.HasFailures |= diff.HasFailures;
            };

            if (hydrateFilesAfterDownload)
            {
                // Call synchronously to ensure that diff.FileAddOperations
                // is completely populated when fileHydrator starts
                performDiff();
            }
            else
            {
                new Thread(performDiff).Start();
            }

            blobFinder.Start();
            downloader.Start();

            if (hydrateFilesAfterDownload)
            {
                fileHydrator.Start();
            }

            // If indexing happens during searching, searching progressively gets slower, so wait on searching before indexing.
            blobFinder.WaitForCompletion();
            this.HasFailures |= blobFinder.HasFailures;

            packIndexer.Start();

            downloader.WaitForCompletion();
            this.HasFailures |= downloader.HasFailures;

            packIndexer.WaitForCompletion();
            this.HasFailures |= packIndexer.HasFailures;

            availableBlobs.CompleteAdding();

            if (hydrateFilesAfterDownload)
            {
                fileHydrator.WaitForCompletion();
                this.HasFailures |= fileHydrator.HasFailures;
            }

            matchedBlobCount    = blobFinder.AvailableBlobCount + blobFinder.MissingBlobCount;
            downloadedBlobCount = blobFinder.MissingBlobCount;
            hydratedFileCount   = fileHydrator.ReadFileCount;

            if (!this.SkipConfigUpdate && !this.HasFailures)
            {
                this.UpdateRefs(branchOrCommit, isBranch, refs);

                if (isBranch)
                {
                    this.HasFailures |= !this.UpdateRefSpec(this.Tracer, this.Enlistment, branchOrCommit, refs);
                }
            }

            if (!this.HasFailures)
            {
                this.SavePrefetchArgs(commitToFetch, hydrateFilesAfterDownload);
            }
        }
Esempio n. 57
0
 public AsyncTestMethod(int iterations, ThreadStart callback, params object[] args)
     : this(iterations, new TestMethod(new ThreadStartTestMethodAdapter(callback).Execute), args)
 {
 }
Esempio n. 58
0
        public static void RunInNewThread(ThreadStart start, int maxStackSize)
        {
            var thread = new Thread(start, maxStackSize);

            thread.Start();
        }
Esempio n. 59
0
 public void StartProcessing()
 {
     _queueProcessThreadStart = new ThreadStart(ProcessThread);
     _queueProcessThread      = new Thread(_queueProcessThreadStart);
     _queueProcessThread.Start();
 }
Esempio n. 60
0
 private void Sub_Thread()
 {
     ThreadStart child = new ThreadStart(CallToChildThread);
 }