Exemplo n.º 1
0
        public static Thread StartNewThread(Action run)
        {
            Thread t = new Thread(run);
            t.Start();

            return t;
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            Random RandomNumber = new Random();

            Thread thread1 = new Thread(new ThreadClass("ONE", RandomNumber).PrintInfo);

            Thread thread2 = new Thread(new ThreadClass("TWO", RandomNumber).PrintInfo);

            Thread thread3 = new Thread(new ThreadClass("THREE", RandomNumber).PrintInfo);

            Thread thread4 = new Thread(new ThreadClass("FOUR", RandomNumber).PrintInfo);

            Thread thread5 = new Thread(new ThreadClass("FIVE", RandomNumber).PrintInfo);

            Thread thread6 = new Thread(new ThreadClass("SIX", RandomNumber).PrintInfo);

            Thread thread7 = new Thread(new ThreadClass("SEVEN", RandomNumber).PrintInfo);

            thread1.Start();
            thread2.Start();
            thread3.Start();
            thread4.Start();
            thread5.Start();
            thread6.Start();
            thread7.Start();
        }
Exemplo n.º 3
0
        protected internal override void QueueTask(Task task)
        {
#if !FEATURE_PAL    // PAL doesn't support  eventing
            if (TplEtwProvider.Log.IsEnabled(EventLevel.Verbose, ((EventKeywords)(-1))))
            {
                Task currentTask = Task.InternalCurrent;
                Task creatingTask = task.m_parent;

                TplEtwProvider.Log.TaskScheduled(this.Id, currentTask == null ? 0 : currentTask.Id, 
                                                 task.Id, creatingTask == null? 0 : creatingTask.Id, 
                                                 (int) task.Options);
            }
#endif

            if ((task.Options & TaskCreationOptions.LongRunning) != 0)
            {
                // Run LongRunning tasks on their own dedicated thread.
                Thread thread = new Thread(s_longRunningThreadWork);
                thread.IsBackground = true; // Keep this thread from blocking process shutdown
                thread.Start(task);
            }
            else
            {
#if PFX_LEGACY_3_5
                ThreadPool.QueueUserWorkItem(s_taskExecuteWaitCallback, (object) task);
#else
                // Normal handling for non-LongRunning tasks.
                bool forceToGlobalQueue = ((task.Options & TaskCreationOptions.PreferFairness) != 0);
                ThreadPool.UnsafeQueueCustomWorkItem(task, forceToGlobalQueue);
#endif
            }
        }
Exemplo n.º 4
0
Arquivo: b.cs Projeto: xyandro/NeoEdit
		public CodeScanner(Action beep, int scanTimeout, int upcLotTimeout)
		{
			this.beep = beep;
			this.ScanTimeout = scanTimeout;
			this.UPCLotTimeout = upcLotTimeout;

			thread = new Thread(ReadScanner);
			thread.Start();
		}
		// This method is invoked when the application has loaded its UI and its ready to run
		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			window.AddSubview (navigation.View);
			
			// this method initializes the main menu Dialog
			var startupThread = new Thread (Startup as ThreadStart);
			startupThread.Start ();
			
			window.MakeKeyAndVisible ();
			return true;
		}
Exemplo n.º 6
0
 private void btnServidor_Click(object sender, EventArgs e)
 {
     TcpListener newSock = new TcpListener(IPAddress.Any, 2000);
     newSock.Start();
     Console.WriteLine("Esperando por cliente");
     while (true)
     {
         TcpClient cliente = newSock.AcceptTcpClient();
         Thread t = new Thread(() => this.handleClient(cliente));
         t.IsBackground = true;
         t.Start();
     }
 }
Exemplo n.º 7
0
 /// <summary>
 /// Schedules a task to the ThreadPool.
 /// </summary>
 /// <param name="task">The task to schedule.</param>
 protected internal override void QueueTask(Task task)
 {
     if ((task.Options & TaskCreationOptions.LongRunning) != 0)
     {
         // Run LongRunning tasks on their own dedicated thread.
         Thread thread = new Thread(s_longRunningThreadWork);
         thread.IsBackground = true; // Keep this thread from blocking process shutdown
         thread.Start(task);
     }
     else
     {
         // Normal handling for non-LongRunning tasks.
         bool forceToGlobalQueue = ((task.Options & TaskCreationOptions.PreferFairness) != 0);
         ThreadPool.UnsafeQueueCustomWorkItem(task, forceToGlobalQueue);
     }
 }
Exemplo n.º 8
0
        public void Execute()
        {
            var checkRunnable = new Runnable(() =>
            {

                const string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                string entity = GenProductArgs();
                var buf = Util.httpPost(url, entity);

                string content = Encoding.Default.GetString(buf);
                _resultunifiedorder = DecodeXml(content);
                VoidPayWindow(content);
            });

            var checkThread = new Thread(checkRunnable);
            checkThread.Start();
        }
Exemplo n.º 9
0
        static void Main()
        {
            string str = string.Empty;
            EventTimer myTimer = new EventTimer(1, DoAction);

            Thread timerThread = new Thread(myTimer.RunTimer);

            timerThread.Start();

            for (int i = 0; i < 100000; i++)
            {
                str += string.Format("{0}Test \r\n", action);
            }

            myTimer.StopTimer();
            Console.WriteLine(str);
        }
Exemplo n.º 10
0
        public static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Thread.CurrentThread.CurrentCulture.ClearCachedData();
            var thread = new Thread(
                s => ((CultureState)s).Result = Thread.CurrentThread.CurrentCulture);
            var state = new CultureState();
            thread.Start(state);
            thread.Join();
            CultureInfo culture = state.Result;

            Localizer.SetCulture(culture);
            Localizer.Initialize();

            Application.Run(new Shell());
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            Random rand = new Random();

            Thread thread1 = new Thread(new ThreadClass("ONE", rand).PrintInfo);

            Thread thread2 = new Thread(new ThreadClass("TWO", rand).PrintInfo);

            Thread thread3 = new Thread(new ThreadClass("THREE", rand).PrintInfo);

            Thread thread4 = new Thread(new ThreadClass("FOUR", rand).PrintInfo);

            Thread thread5 = new Thread(new ThreadClass("FIVE", rand).PrintInfo);

            thread1.Start();
            thread2.Start();
            thread3.Start();
            thread4.Start();
            thread5.Start();
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            Debug.WriteLine("inSSIDer 2 version " + Application.ProductVersion + " Starting");
            //TODO: Make conmmand line option to enable logging on debug builds. Like /log
            #if DEBUG && LOG
            Log.Start();
            #endif
            Debug.WriteLine("Hook exception handlers");
            // Create new instance of UnhandledExceptionDlg:
            // NOTE: this hooks up the exception handler functions
            UnhandledExceptionDlg exDlg = new UnhandledExceptionDlg();
            InitializeExceptionHandler(exDlg);

            Debug.WriteLine("Check .NET configuration system");
            //Check for config system condition here
            if(!Settings.Default.CheckSettingsSystem())
            {
                //The settings system is broken, notify and exit
                MessageBox.Show(
                    Localizer.GetString("ConfigSystemError"),
                    "Error", MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            #if DEBUG && LOG
            frmTest ft = new frmTest();
            Thread debugThread = new Thread(() => Application.Run(ft));
            debugThread.Start();
            #endif

            //Initialize the scanner object before passing it to any interface
            ScanController scanner = new ScanController();
            Exception error;

            Debug.WriteLine("Initialize ScanController");
            scanner.Initialize(out error);
            if (error != null)
            {
                //An error!
                scanner.Dispose();
                scanner = null;
                //So the error handler will catch it
                //throw ex;

                //Log it
                Log.WriteLine(string.Format("Exception message:\r\n\r\n{0}\r\n\r\nStack trace:\r\n{1}", error.Message, error.StackTrace));

                if (error is System.ComponentModel.Win32Exception)
                {
                    //The wireless system failed
                    if (Utilities.IsXp())
                    {
                        MessageBox.Show(Localizer.GetString("WlanServiceNotFoundXP"), "Error", MessageBoxButtons.OK,
                                        MessageBoxIcon.Hand);
                    }
                    else
                    {
                        MessageBox.Show(Localizer.GetString("WlanServiceNotFound7"), "Error", MessageBoxButtons.OK,
                                        MessageBoxIcon.Hand);
                    }
                }
                else
                {
                    //Any other exceptions
                    MessageBox.Show(error.Message, "Error", MessageBoxButtons.OK,
                                        MessageBoxIcon.Hand);
                }
            }

            if (scanner == null) return;

            //Start the scanning if it was last time and we have the last interface
            //Otherwise, if we only have the interface, but not scanning, just set the interface selector to the last interface.
            //TODO: Actually have the auto-start as an option. :)

            NetworkInterface netInterface = InterfaceManager.Instance.LastInterface;
            if (netInterface != null)
            {
                Debug.WriteLine("We have a last interface, start scanning with it.");
                //Set the interface
                scanner.Interface = netInterface;
                if (Settings.Default.scanLastEnabled)
                    scanner.StartScanning();
            }

            //The main form will run unless mini is specified
            IScannerUi form = null;

            Switching = Settings.Default.lastMini ? Utilities.SwitchMode.ToMini : Utilities.SwitchMode.ToMain;

            //if(Settings.Default.lastMini)
            //{
            //    Switching = Utilities.SwitchMode.ToMini;
            //    form = new FormMini();
            //    SettingsMgr.ApplyMiniFormSettings((Form)form);
            //}
            //else
            //{
            //    Switching = Utilities.SwitchMode.ToMain;
            //    form = new FormMain();
            //    SettingsMgr.ApplyMainFormSettings((Form)form);
            //}

            //Apply settings now
            SettingsMgr.ApplyGpsSettings(scanner.GpsControl);

            do
            {
                //Check for switching
                switch (Switching)
                {
                    case Utilities.SwitchMode.None:
                        //We're not switching, close program
                        break;
                    case Utilities.SwitchMode.ToMain:
                        //We're switching to the main form
                        Debug.WriteLine("Switch to main form");
                        form = new FormMain(scanner);
                        SettingsMgr.ApplyMainFormSettings((Form)form);
                        break;
                    case Utilities.SwitchMode.ToMini:
                        //We're switching to the mini form
                        Debug.WriteLine("Switch to mini form");
                        form = new FormMini();
                        SettingsMgr.ApplyMiniFormSettings((Form)form);
                        break;
                }
                LastSwitch = Switching;
                //If we've switched, we don't need to get stuck in a loop
                Switching = Utilities.SwitchMode.None;

                form.Initalize(ref scanner);
                try
                {
                    Application.Run(form as Form);
                }
                catch (ObjectDisposedException)
                {

                }
                catch (AccessViolationException)
                {
                    Debug.WriteLine("AccessViolationException, attempt to recover");
                    if (Application.VisualStyleState == System.Windows.Forms.VisualStyles.VisualStyleState.NonClientAreaEnabled)
                        throw;
                    // This could be caused by visual styles
                    Application.VisualStyleState = System.Windows.Forms.VisualStyles.VisualStyleState.NonClientAreaEnabled;
                    // Trigger restart
                    Switching = LastSwitch;//Utilities.SwitchMode.ToMain;
                }

            } while (Switching != Utilities.SwitchMode.None);

            Settings.Default.lastMini = form.GetType() == typeof(FormMini);

            if(scanner.GpsControl != null)
            //GPS enabled setting
            Settings.Default.gpsEnabled = scanner.GpsControl.Enabled;

            // Save Filters

            //Save settings before exit
            Settings.Default.Save();

            //Dispose the scanner, we're done with it
            scanner.Dispose();

            Debug.WriteLine("Execution Finished, you may now close this window", "Program.Main()");
        }
Exemplo n.º 13
0
        private void AlipayPay(object sender, EventArgs args)
        {


            if (!AliPayHelper.CheckConfig())
            {
                Toast.MakeText(ApplicationContext,
                    "系统异常.",
                    ToastLength.Long);
                Log.Error(Tag, "Aplipay Config Exception ");
                return;
            }
            string payInfo = AliPayHelper.GetPayInfo();
            // 完整的符合支付宝参数规范的订单信息
            Runnable payRunnable = new Runnable(() =>
            {
                PayTask alipay = new PayTask(this);
                // 调用支付接口,获取支付结果
                string result = alipay.Pay(payInfo);

                Message msg = new Message
                {
                    What = (int)MsgWhat.AlipayPayFlag,
                    Obj = result
                };
                _handler.SendMessage(msg);
            });

            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.Start();
        }
Exemplo n.º 14
0
        /**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
        public void check(object o, EventArgs e)
        {
            Runnable checkRunnable = new Runnable(()=> {
                PayTask payTask = new PayTask(this);
                // 调用查询接口,获取查询结果
                bool isExist = payTask.CheckAccountIfExist();

                Message msg = new Message();
                msg.What = SDK_CHECK_FLAG;
                msg.Obj = isExist;
                mHandler.SendMessage(msg);
            });

            Thread checkThread = new Thread(checkRunnable);
            checkThread.Start();

        }
Exemplo n.º 15
0
        public void pay(object o, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(PARTNER) || string.IsNullOrWhiteSpace(RSA_PRIVATE)
                    || string.IsNullOrWhiteSpace(SELLER))
            {
                new AlertDialog.Builder(this)
                        .SetTitle("警告")
                        .SetMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
                        .SetPositiveButton("确定", (dialoginterface, i) => { Finish(); }

                                ).Show();
                return;
            }
            // 订单
            string orderInfo = GetOrderInfo("测试的商品", "该测试商品的详细描述", "0.01");

            // 对订单做RSA 签名
            string sign = Sign(orderInfo);
            try
            {
                // 仅需对sign 做URL编码
                sign = Java.Net.URLEncoder.Encode(sign, "UTF-8");
            }
            catch (UnsupportedEncodingException ex)
            {
                ex.PrintStackTrace();
            }
            finally
            {
                string payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                                + GetSignType();
                // 完整的符合支付宝参数规范的订单信息
                Runnable payRunnable = new Runnable(()=> {
                    PayTask alipay = new PayTask(this);
                    // 调用支付接口,获取支付结果
                    string result = alipay.Pay(payInfo);

                    Message msg = new Message();
                    msg.What = SDK_PAY_FLAG;
                    msg.Obj = result;
                    mHandler.SendMessage(msg);
                });
                
                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.Start();
            }


        }
Exemplo n.º 16
0
        private static void AddRef(IntPtr ptr)
        {
#if REFDEBUG
            if (refdumper == null)
            {
                refdumper = new Thread(dumprefs);
                refdumper.IsBackground = true;
                refdumper.Start();
            }
#endif
            lock (reflock)
            {
                if (!_refs.ContainsKey(ptr))
                {
#if REFDEBUG
                    Console.WriteLine("Adding a new reference to: " + ptr + " (" + 0 + "==> " + 1 + ")");
#endif
                    _refs.Add(ptr, 1);
                }
                else
                {
#if REFDEBUG
                    Console.WriteLine("Adding a new reference to: " + ptr + " (" + _refs[ptr] + "==> " + (_refs[ptr] + 1) + ")");
#endif
                    _refs[ptr]++;
                }
            }
        }
Exemplo n.º 17
0
        private void RunInWorkerThread(Action runHandler)
        {
            try
            {
                _workerThread = new Thread(() =>
                    {
                        try
                        {
                            runHandler();
                        }
                        catch (Exception e)
                        {
                            Kp2aLog.Log("Error in worker thread of SaveDb: " + e);
                            Finish(false, e.Message);
                        }

                    });
                _workerThread.Start();
            }
            catch (Exception e)
            {
                Kp2aLog.Log("Error starting worker thread of SaveDb: "+e);
                Finish(false, e.Message);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates the a talk window form and show it. Restores talk window
        /// contents if configuredto do so.  Raises an event indicating the
        /// talk window was created.  Window creation is done in a separate
        /// thread with its own message loop
        /// </summary>
        private void createAndShowTalkWindow()
        {
#if TALKWINDOW_DISPATCHER_THREAD
            var viewerThread = new Thread(delegate()
            {
                if (!_inTalkWindowCreationThread)
                {
                    _inTalkWindowCreationThread = true;

                    // Create our context, and install it:
                    SynchronizationContext.SetSynchronizationContext(
                        new System.Windows.Threading.DispatcherSynchronizationContext(
                            System.Windows.Threading.Dispatcher.CurrentDispatcher));
#endif
            IsTalkWindowActive = true;

            CreateTalkWindow();

            showGlass();

            Windows.SetTopMost(_talkWindowForm);

            Form form = null;
            if (PanelManager.Instance.GetCurrentForm() != null)
            {
                form = PanelManager.Instance.GetCurrentForm() as Form;
            }

            if (form != null)
            {
                SetTalkWindowPosition(PanelManager.Instance.GetCurrentForm() as Form);
            }


            var talkWindowAgent = Context.AppAgentMgr.GetAgentByName("TalkWindow Agent");
            Log.IsNull("Talkwindowagent", talkWindowAgent);
            if (talkWindowAgent != null)
            {
                Context.AppAgentMgr.AddAgent(_talkWindowForm.Handle, talkWindowAgent);
                Log.Debug("Added talkwindowagent");
            }

            Windows.ShowForm(_talkWindowForm);

            Windows.ActivateForm(_talkWindowForm);

            AuditLog.Audit(new AuditEventTalkWindow("show"));

            if (CoreGlobals.AppPreferences.RetainTalkWindowContentsOnHide)
            {
                _talkWindow.TalkWindowText = _talkWindowText;
            }

            if (EvtTalkWindowCreated != null)
            {
                EvtTalkWindowCreated(this, new TalkWindowCreatedEventArgs(_talkWindowForm));
            }

#if TALKWINDOW_DISPATCHER_THREAD
                    System.Windows.Threading.Dispatcher.Run();
                    Log.Debug("Exited DISPATCHER.RUN");
                    _inTalkWindowCreationThread = false;
                }
            });

            viewerThread.SetApartmentState(ApartmentState.STA);
            Log.Debug("Starting thread, _inTalkWindowCreationThread is :  " + _inTalkWindowCreationThread);
            viewerThread.Start();
#endif
        }
Exemplo n.º 19
0
 public void Resume()
 {
     running = true;
     renderThread = new Thread (this);
     renderThread.Start ();
 }
Exemplo n.º 20
0
		void ParseParallel (ModuleContainer module)
		{
			var sources = module.Compiler.SourceFiles;

			Location.Initialize (sources);

			var pcount = Environment.ProcessorCount;
			var threads = new Thread[System.Math.Max (2, pcount - 1)];

			for (int i = 0; i < threads.Length; ++i) {
				var t = new Thread (l => {
					var session = new ParserSession () {
						//UseJayGlobalArrays = true,
					};

					var report = new Report (ctx, Report.Printer); // TODO: Implement flush at once printer

					for (int ii = (int) l; ii < sources.Count; ii += threads.Length) {
						Parse (sources[ii], module, session, report);
					}

					// TODO: Merge warning regions
				});

				t.Start (i);
				threads[i] = t;
			}

			for (int t = 0; t < threads.Length; ++t) {
				threads[t].Join ();
			}
		}