//private const string USER_AGENT = "Mozilla/5.0 (X11; U; Linux x86_64; en_US; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8";
 public Form1()
 {
     settings = new Properties.Settings();
     settings.Reload();
     InitializeComponent();
     edtUsername.Text = settings.username;
     //edtPassword.Text = settings.password;
     if (settings.password != "")
     {
         UTF8Encoding encoding = new UTF8Encoding();
         byte[] encPwd = Convert.FromBase64String(settings.password);
         //byte[] encPwd = encoding.GetBytes(settings.password);
         byte[] decPwd = {};
         try
         {
             decPwd = ProtectedData.Unprotect(encPwd, additionalEntropy, DataProtectionScope.CurrentUser);
         }
         catch (CryptographicException e)
         {
             MessageBox.Show("Error decrypting user password. Defaulting to blank password.");
             //decPwd = encoding.GetBytes("");
             //decPwd = {};
         }
         edtPassword.Text = encoding.GetString(decPwd);
     }
     threadDelegate1 = new ThreadDelegate(updateProgress);
     threadDelegate2 = new ThreadDelegate2(updateStatus);
     keyHandled = false;
     this.KeyDown += Form1_KeyDown;
     this.KeyPress += Form1_KeyPress;
 }
Beispiel #2
0
        public DEThreadList(IServiceProvider sp, string categoryName, string name, ThreadDelegate threadStart)
        {
            if (sp == null)
            {
                throw new ArgumentNullException("sp");
            }
            if (String.IsNullOrEmpty(categoryName))
            {
                throw new ArgumentNullException("categoryName");
            }
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            if (threadStart == null)
            {
                throw new ArgumentNullException();
            }

            this.sp           = sp;
            this.categoryName = categoryName;
            this.name         = name;

            this.threadStart = threadStart;
        } // ctor
Beispiel #3
0
        static void Main(string[] args)
        {
            ThreadDelegate TD = new ThreadDelegate(ThreadMethod);
            ThreadStart    TS = new ThreadStart(TD);

            for (int i = 0; i < 4; i++)
            {
                Thread T = new Thread(TS);
                T.Name         = String.Format($"T{i}");
                T.IsBackground = true;
                T.Start();
                if (i == 2)
                {
                    T.Priority = ThreadPriority.Lowest;
                }
                else
                {
                    T.Priority = ThreadPriority.AboveNormal;
                }
            }

            while (true)
            {
                if (Equals(ConsoleKey.Escape, Console.ReadKey().Key))
                {
                    break;
                }
            }
        }
Beispiel #4
0
 public void start(MainWindow window, ThreadDelegate method)
 {
     /*Random rand = new Random();
      * while (true)
      * {
      *  window.Dispatcher.BeginInvoke(method, new Point(rand.NextDouble(), rand.NextDouble())); // direct + indirect
      *  Thread.Sleep(60);
      * }*/
     while (true)
     {
         int receiveLength = clientSocket.Receive(result);
         //Console.WriteLine("接收服务器消息:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
         total = Encoding.ASCII.GetString(result, 0, receiveLength);
         //Console.WriteLine(total);
         string[] spt   = total.Split(',');// Regex.Split(total, ",", RegexOptions.IgnoreCase);
         double[] coord = new double[2];
         int      z     = 0;
         foreach (string i in spt)
         {
             coord[z] = Convert.ToDouble(i);
             z++;
         }
         // Console.WriteLine("x={0},y={1}",coord[0], coord[1]);
         window.Dispatcher.BeginInvoke(method, new Point(coord[0], coord[1])); // direct + indirect
     }
 }
        public void Start( ThreadDelegate method )
        {
            SynchronizationContext context = SynchronizationContext.Current;

            // if there is no synchronization, don't launch a new thread
            if ( context != null )
            {
                // new thread to execute the Load() method for the layer
                new Thread( ( ) =>
                {
                    method.DynamicInvoke( );

                    //// fire the OnLoadComplete event on the original thread
                    //context.Post( new SendOrPostCallback( ( obj ) =>
                    //{
                    //    add callback method call here if needed in future
                    //} ), null );

                } ).Start( );
            }
            else
            {
                method.DynamicInvoke( );
            }
			
        }
Beispiel #6
0
 static void Main(string[] args)
 {
     ThreadDelegate TD = new ThreadDelegate(ThreadMethod);
     ThreadStart TS = new ThreadStart(TD);
     for (int i = 0; i < 4; i++)
     {
         Thread T = new Thread(TS);
         T.Name = String.Format($"T{i}");
         T.IsBackground = true;
         T.Start();
         if (i==2)
         {
             T.Priority = ThreadPriority.Lowest;
         }
         else
         {
             T.Priority = ThreadPriority.AboveNormal;
         }
     }
     
     while(true)
     {
         if(Equals(ConsoleKey.Escape, Console.ReadKey().Key))
         {
             
             break;
         }
     }
 }
Beispiel #7
0
        private void updateGUI()
        {
            gridUpdate = dataGridUpdate;
            ThreadDelegate resizeGrid = dataGridViewValues.AutoResizeColumns;

            try
            {
                bool alive = true;
                while (alive)
                {
                    if (refresh)
                    {
                        Invoke(gridUpdate);
                        refresh = false;
                    }
                    if (searchThread == null || !searchThread.IsAlive)
                    {
                        alive = false;
                    }

                    Thread.Sleep(500);
                }
            }
            finally
            {
                Invoke(gridUpdate);
                Invoke(resizeGrid);
            }
        }
Beispiel #8
0
        public DEThread(IServiceProvider sp, string name, ThreadDelegate action, string categoryName = ThreadCategory, ThreadPriority priority = ThreadPriority.Normal, bool isBackground = false, ApartmentState apartmentState = ApartmentState.MTA)
            : base(sp, name, categoryName)
        {
            this.action = action;

            StartThread(name, priority, isBackground, apartmentState);
        } // ctor
Beispiel #9
0
        async private void Button_Click(object sender, RoutedEventArgs e)
        {
            rtts.Clear();
            PingButton.IsEnabled = false;
            pingcomplete         = false;
            lastseq         = 0;
            cancelrequested = false;
            singlecomplete  = false;
            storenumber     = "";
            window2.LogBox2.AppendText("\n=======" + Convert.ToString(DateTime.Now) + "=======\n");
            await progressbar.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadDelegate(new Action(() => UpdateProgressbar(0))));

            await CancelButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadDelegate(EnableCancelButton));

            await Outputfield.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadDelegate(clearoutbox));

            await StatisticsBox.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadDelegate(UpdateBox0));

            await Task.Factory.StartNew(() => ParseInput());

            ThreadDelegate pinger = new ThreadDelegate(Repeaticmp);

            pinger.BeginInvoke(null, null);
            //ThreadDelegate parser = new ThreadDelegate(ParseInput);
            //parser.BeginInvoke(null, null);
        }
Beispiel #10
0
        // Instructs the ThreadPool class to run the given Jibu task with the given priority and
        // synchronizing on the provided barrier.
        internal static void runTask(ThreadDelegate task, ThreadPriority priority)
        {
            JibuThread thread = JibuThreadPool.getThread();

            thread.setPriority(priority);
            thread.Task = task;
            thread.runThread();
        }
Beispiel #11
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="thread"></param>
 /// <param name="threadDelegate"></param>
 public virtual void CreateAndStartThread(Thread thread, ThreadDelegate threadDelegate)
 {
     if (thread == null)
     {
         thread = new Thread(new ThreadStart(threadDelegate));
         thread.IsBackground = true;
         thread.Start();
     }
 }
        private void PrintScreen(int x, int y, int w, int h)
        {
            if (w < 0)
            {
                w = (int)SystemParameters.PrimaryScreenWidth;
            }
            if (h < 0)
            {
                h = (int)SystemParameters.PrimaryScreenHeight;
            }
            Bitmap   printscreen = new Bitmap(w, h);
            Graphics graphics    = Graphics.FromImage(printscreen as System.Drawing.Image);

            graphics.CopyFromScreen(x, y, 0, 0, printscreen.Size);
            var fileStream = new FileStream("screenshot.png", FileMode.Create);

            printscreen.Save(fileStream, ImageFormat.Png);
            fileStream.Close();

            MemoryStream ms = new MemoryStream();

            printscreen.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            ms.Position = 0;
            BitmapImage bi = new BitmapImage();

            bi.BeginInit();
            bi.StreamSource = ms;
            bi.EndInit();
            imagebox1.Source = bi;

            if (w / h > 470d / 240)
            {
                imagebox1.Width  = 470;
                imagebox1.Height = 470d / w * h;
            }
            else
            {
                imagebox1.Height = 240;
                imagebox1.Width  = 240d / h * w;
            }

            client.uploading  = true;
            label1.Opacity    = 1;
            button1.IsEnabled = false;
            label1.Content    = "Uploading...";
            if (this.Height == 210)
            {
                DoubleAnimation myAnimation = new DoubleAnimation(210, 470, new Duration(new TimeSpan(0, 0, 0, 0, 300)));
                this.BeginAnimation(HeightProperty, myAnimation);
            }

            Window_GoShow();

            ThreadDelegate backWorkDel = new ThreadDelegate(UploadPhoto);

            backWorkDel.BeginInvoke(null, null);
        }
        public void TaskEndedByCatchD(Task <Checkin_ltjyStack> task)
        {
            if (task.IsCompleted)
            {
                Checkin_ltjyStack TaskResult = task.Result;
                if (TaskResult.Status.Contains("成功"))
                {
                    IEnumerator ienumerator = App.ListCheckin_ltjyStack.GetEnumerator();
                    int         count       = 0;
                    while (ienumerator.MoveNext())
                    {
                        if (((Checkin_ltjyStack)ienumerator.Current).CRIB == TaskResult.CRIB)
                        {
                            App.ListCheckin_ltjyStack[count].Status = TaskResult.Status;
                            App.ListCheckin_ltjyStack[count].LISTPD_SIMPLE.ForEach(Ltjy => Ltjy.status = "同步成功");
                            ThreadDelegate TetBoxDel2 = delegate()
                            {
                                PackCountTxt_Copy.Content = Tools.GetSendStatus(true).ToString();
                            };
                            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, TetBoxDel2);
                            return;
                        }
                        count++;
                    }
                }
                else
                {
                    IEnumerator ienumerator = App.ListCheckin_ltjyStack.GetEnumerator();
                    int         ecount      = 0;
                    while (ienumerator.MoveNext())
                    {
                        Checkin_ltjyStack _Checkin_ltjyStack = (Checkin_ltjyStack)ienumerator.Current;

                        if (_Checkin_ltjyStack != null)
                        {
                            if (_Checkin_ltjyStack.CRIB == TaskResult.CRIB)
                            {
                                ThreadDelegate TetBoxDel2 = delegate()
                                {
                                    PackCountStackE.Content = Tools.GetSendStatus(false).ToString();
                                };
                                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, TetBoxDel2);

                                App.ListCheckin_ltjyStack[ecount].CRIB   = TaskResult.CRIB;
                                App.ListCheckin_ltjyStack[ecount].Status = TaskResult.Status;
                                App.ListCheckin_ltjyStack[ecount].LISTPD_SIMPLE.Clear();
                                App.ListCheckin_ltjyStack[ecount].LISTPD_SIMPLE.AddRange(TaskResult.LISTPD_SIMPLE);
                                return;
                            }
                        }
                        ecount++;
                    }
                }
                Tools.Serialize(App.ListCheckin_ltjyStack);
            }
        }
 public static void SpawnThreads(int threads)
 {
     for (int i = 0; i < threads; i++)
     {
         ThreadDelegate del = new ThreadDelegate(CallProxy);
         IAsyncResult result = del.BeginInvoke(delegate(IAsyncResult r)
         {
             EndCall(del.EndInvoke(r));
         }, null);
     }
 }
 public static void SpawnThreads(int threads)
 {
     for (int i = 0; i < threads; i++)
     {
         ThreadDelegate del    = new ThreadDelegate(CallProxy);
         IAsyncResult   result = del.BeginInvoke(delegate(IAsyncResult r)
         {
             EndCall(del.EndInvoke(r));
         }, null);
     }
 }
Beispiel #16
0
        /// <summary>
        ///  利用BAT复制文件
        /// </summary>
        private void CopyFile()
        {
            RunBat(AppDomain.CurrentDomain.BaseDirectory + "CopyFile.bat"); //运行Bat文件
            ThreadDelegate changeTetBoxDel = delegate()                     //后台中要更改主线程中的UI,于是我们还是用委托来实现,再创建一个实例
            {
                Prog.IsIndeterminate = false;
                Prog.Visibility      = Visibility.Hidden;
                NXCrack.IsEnabled    = true;
                ModernDialog.ShowMessage(Version.Text + " 破解完成,请继续安装许可证!", "提示", MessageBoxButton.OK);
                File.Delete(AppDomain.CurrentDomain.BaseDirectory + "CopyFile.bat");
            };                                                                     //要调用的过程

            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, changeTetBoxDel); //使用分发器让这个委托等待执行
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (windowsmall == true)
            {
                Task.Factory.StartNew(() => GrowWindow());
            }
            Task startNew = Task.Factory.StartNew(() => TheMagic());

            startNew.Wait();
            PortScanProgress.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadDelegate(new Action(() => PortScanProgress.Fill = Brushes.Salmon)));
            ThreadDelegate updater = new ThreadDelegate(UpdateInterface);

            updater.BeginInvoke(null, null);
        }
Beispiel #18
0
        /// <summary>
        /// Parallel for loop. Invokes given action, passing arguments
        /// fromInclusive - toExclusive on multiple threads.
        /// Returns when loop finished.
        /// </summary>
        /// <remarks>Source: http://coding-time.blogspot.com/2008/03/implement-your-own-parallelfor-in-c.html</remarks>
        public static void For(int fromInclusive, int toExclusive, ForDelegate action)
        {
            // ChunkSize = 1 makes items to be processed in order.
            // Bigger chunk size should reduce lock waiting time and thus
            // increase paralelism.
            int chunkSize = 4;

            // number of process() threads
            int threadCount = Environment.ProcessorCount;
            int cnt         = fromInclusive - chunkSize;

            // processing function
            // takes next chunk and processes it using action
            ThreadDelegate process = delegate()
            {
                while (true)
                {
                    int cntMem = 0;
                    lock (typeof(Parallel))
                    {
                        // take next chunk
                        cnt   += chunkSize;
                        cntMem = cnt;
                    }
                    // process chunk
                    // here items can come out of order if chunkSize > 1
                    for (int i = cntMem; i < cntMem + chunkSize; ++i)
                    {
                        if (i >= toExclusive)
                        {
                            return;
                        }
                        action(i);
                    }
                }
            };

            // launch process() threads
            IAsyncResult[] asyncResults = new IAsyncResult[threadCount];
            for (int i = 0; i < threadCount; ++i)
            {
                asyncResults[i] = process.BeginInvoke(null, null);
            }
            // wait for all threads to complete
            for (int i = 0; i < threadCount; ++i)
            {
                process.EndInvoke(asyncResults[i]);
            }
        }
Beispiel #19
0
        static void ReadWriterLockSlimDemo()
        {
            Console.WriteLine("ReadWriterLockSlim demo");

            var random = new Random();

            // The data the threads will attempt to manipulate
            var hiscore_table = new HiscoreTable();

            // Create a few worker threads
            const int NUM_THREADS = 10;
            var       threads     = new Thread[NUM_THREADS];

            // Assign random tasks to the threads
            for (int i = 0; i < NUM_THREADS; i++)
            {
                ThreadDelegate thread_delegate = () => {};
                switch (random.Next(3))
                {
                case 0:
                    thread_delegate = () => TeslaTest(hiscore_table);
                    break;

                case 1:
                    thread_delegate = () => EdisonTest(hiscore_table);
                    break;

                case 2:
                    thread_delegate = () => FaradayTest(hiscore_table);
                    break;
                }
                threads[i]      = new Thread(new ThreadStart(thread_delegate));
                threads[i].Name = String.Format("Thread {0}", i);
            }

            // Start the threads
            for (int i = 0; i < NUM_THREADS; i++)
            {
                threads[i].Start();
            }

            // Block until all threads are finished
            for (int i = 0; i < NUM_THREADS; i++)
            {
                threads[i].Join();
            }

            Console.Write(Environment.NewLine);
        }
Beispiel #20
0
        /// <summary>
        /// Starts a new thread invoking the specified method.
        /// </summary>
        /// <param name="method">The method to invoke.</param>
        public void Start(ThreadDelegate method)
        {
            SynchronizationContext context = SynchronizationContext.Current;

            // if there is no synchronization, don't launch a new thread
            if (context != null)
            {
                // new thread to execute the Load() method for the layer
                new Thread(() => method.DynamicInvoke()).Start();
            }
            else
            {
                method.DynamicInvoke();
            }
        }
Beispiel #21
0
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                _threadFuncDelegate = null;
            }

            WinApiHelper.WaitForSingleObject(Handle, 10000);
            WinApiHelper.CloseHandle(Handle);

            _disposed = true;
        }
Beispiel #22
0
        public Splash()
        {
            InitializeComponent();

            contentDelegate = delegate()
            {
                ChangeContent(content);
            };
            closeDelegate = delegate()
            {
                Close();
            };

            Thread t = new Thread(new ThreadStart(Show));

            t.Start();
        }
Beispiel #23
0
        public void start_surf(MainWindow window, ThreadDelegate method)
        {
            while (true)
            {
                int receiveLength = clientSocket.Receive(result);
                total = Encoding.ASCII.GetString(result, 0, receiveLength);
                Console.WriteLine(total);
                string[] spt   = Regex.Split(total, "js", RegexOptions.IgnoreCase);
                double[] coord = new double[2];
                int      z     = 0;
                foreach (string i in spt)
                {
                    coord[z] = Convert.ToDouble(i);
                }

                window.Dispatcher.BeginInvoke(method, new Point(coord[0], coord[1])); // direct + indirect
            }
        }
Beispiel #24
0
        /// <summary>
        ///  破解NX文件
        /// </summary>
        /// <param name="Versions">NX注册表版本,如"Unigraphics V28.0"</param>
        private void PJFile(string Version)
        {
            ///创建bat批处理文件
            string Path = "xcopy " + "\"" + PJRoute.Text + "\"" + " " + "\"" + GetNXPath(Version) + "\"" + " /c /e /r /y";

            File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "CopyFile.bat", Path, Encoding.Default);

            ///采用多线程运行bat复制文件
            Prog.Visibility      = Visibility.Visible; //进度条显示
            Prog.IsIndeterminate = true;               //切换进度条显示模式
            NXCrack.IsEnabled    = false;              //破解按钮不可选

            ///创建一个ThreadDelegate的实例,调用准备在后台运行的函数
            ThreadDelegate backWorkDel = new ThreadDelegate(CopyFile);

            ///使用异步的形式开始执行这个委托
            backWorkDel.BeginInvoke(null, null);
        }
 /// <summary>
 /// 线程结束后的结果处理,监测数据同步状态
 /// </summary>
 /// <param name="task"></param>
 public void TaskEndedByCatch(Task <string> task)
 {
     if (task.IsCompleted)
     {
         if (PackData_Simpl == null)
         {
             return;
         }
         string _result = task.Result.ToString();
         if (_result.ToUpper().Contains("ERROR"))
         {
             for (int k = 0; k < PackData_Simpl.Count; k++)
             {
                 if (_result.ToUpper().Contains(PackData_Simpl[k].barcode))
                 {
                     PackData_Simpl[k].status = _result;
                     ThreadDelegate TetBoxDel2 = delegate()
                     {
                         textpackError.Text = Tools.PackData_Simpl_Error.Count.ToString();
                     };
                     this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, TetBoxDel2); //启动委托
                 }
             }
         }
         else
         {
             for (int k = 0; k < PackData_Simpl.Count; k++)
             {
                 if (PackData_Simpl[k].barcode == _result)
                 {
                     PackData_Simpl[k].status = "上传成功";
                     Tools.SendCount++;
                     ThreadDelegate TetBoxDel = delegate()
                     {
                         textSendCount.Text        = Tools.SendCount.ToString();
                         PackCountTxt_Copy.Content = Tools.SendCount.ToString();
                     };
                     this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, TetBoxDel); //启动委托
                 }
             }
         }
     }
 }
        public void DeletePackdata(string text)
        {
            ThreadDelegate changeTetBoxDel = delegate()
            {
                string _code = Tools.ReplaceScanWord(text);
                if (PackData_Simpl != null)
                {
                    for (int k = 0; k < PackData_Simpl.Count; k++)
                    {
                        if (PackData_Simpl[k].barcode == _code)
                        {
                            PackData_Simpl.RemoveAt(k);
                        }
                    }
                }
            };

            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, changeTetBoxDel); //启动委托
        }
Beispiel #27
0
        static void Main(string[] args)
        {
            object[] myCollect =
            {
                new Point(2,     4),
                new Exception(),
                new Button(),
                new TextBox(),
                new Label()
            };

            ThreadDelegate td = new ThreadDelegate(ThreadMethod);

            Console.WriteLine("Main Threading ID is: " + Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("Begin Invoke!!!:");

            td.BeginInvoke(myCollect, null, null);

            Console.ReadLine();
        }
 private string UploadPhoto()
 {
     try
     {
         PicasaService service = new PicasaService("picasaupload");
         service.setUserCredentials(user.email, user.password);
         var         file       = "screenshot.png";
         var         fileStream = new FileStream(file, FileMode.Open);
         PicasaEntry entry      = (PicasaEntry)service.Insert(new Uri("https://picasaweb.google.com/data/feed/api/user/default/albumid/default"), fileStream, "image/jpeg", file);
         fileStream.Close();
         PhotoAccessor  ac           = new PhotoAccessor(entry);
         string         albumId      = ac.AlbumId;
         string         photoId      = ac.Id;
         string         contentUrl   = entry.Media.Content.Attributes["url"] as string;
         ThreadDelegate UploadFinish = delegate()
         {
             client.pid        = photoId;
             client.uploading  = false;
             label1.Opacity    = 0;
             button1.IsEnabled = true;
             button1.Content   = "Share";
             return("succeed");
         };
         this.Dispatcher.BeginInvoke(DispatcherPriority.Send, UploadFinish);
         return("succeed");
     }
     catch (Exception ex)
     {
         ThreadDelegate UploadFinish = delegate()
         {
             label1.Content   = "Upload failed";
             client.uploading = false;
             return("fail");
         };
         this.Dispatcher.BeginInvoke(DispatcherPriority.Send, UploadFinish);
         return("fail");
     }
 }
Beispiel #29
0
        public void Start(ThreadDelegate method)
        {
            SynchronizationContext context = SynchronizationContext.Current;

            // if there is no synchronization, don't launch a new thread
            if (context != null)
            {
                // new thread to execute the Load() method for the layer
                new Thread(() =>
                {
                    method.DynamicInvoke( );

                    //// fire the OnLoadComplete event on the original thread
                    //context.Post( new SendOrPostCallback( ( obj ) =>
                    //{
                    //    add callback method call here if needed in future
                    //} ), null );
                }).Start( );
            }
            else
            {
                method.DynamicInvoke( );
            }
        }
Beispiel #30
0
 public ThreadAction(Action <IntPtr> action)
 {
     this._Delegate       = new ThreadDelegate(action);
     this.FunctionPointer = Marshal.GetFunctionPointerForDelegate(this._Delegate);
 }
Beispiel #31
0
 /// <summary>
 /// Starts a new thread invoking the specified method.
 /// </summary>
 /// <param name="method">The method to invoke.</param>
 public void Start(ThreadDelegate method)
 {
     method.DynamicInvoke();
 }
Beispiel #32
0
        private void ManageProgress(BindingSource bindingSource, DoubleBufferedDataGridView grid, FrameType frameType,
                                    int sleepTimer)
        {
            var progress = new Progress();

            progress.SetupAndShow(this, 0, 0, false, true, waitHandle);

            progressSearched = 0;
            progressFound    = 0;

            UpdateGridDelegate gridUpdater = UpdateGrid;
            var updateParams = new object[] { bindingSource };
            ResortGridDelegate gridSorter       = ResortGrid;
            var            sortParams           = new object[] { bindingSource, grid, frameType };
            ThreadDelegate enableGenerateButton = EnableSeedGenerate;

            try
            {
                bool alive = true;
                while (alive)
                {
                    progress.ShowProgress(progressSearched / (float)progressTotal, progressSearched, progressFound);
                    if (refreshQueue)
                    {
                        Invoke(gridUpdater, updateParams);
                        refreshQueue = false;
                    }
                    if (jobs != null)
                    {
                        foreach (Thread job in jobs)
                        {
                            if (job != null && job.IsAlive)
                            {
                                alive = true;
                                break;
                            }
                            alive = false;
                        }
                    }
                    if (sleepTimer > 0)
                    {
                        Thread.Sleep(sleepTimer);
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                // This keeps the program from crashing when the Time Finder progress box
                // is closed from the Windows taskbar.
            }
            catch (Exception exception)
            {
                if (exception.Message != "Operation Cancelled")
                {
                    throw;
                }
            }
            finally
            {
                progress.Finish();

                if (jobs != null)
                {
                    for (int i = 0; i < jobs.Length; i++)
                    {
                        if (jobs[i] != null)
                        {
                            jobs[i].Abort();
                        }
                    }
                }

                Invoke(enableGenerateButton);
                Invoke(gridSorter, sortParams);
            }
        }
Beispiel #33
0
 public GThread()
 {
     _threadFuncDelegate += CalculatePi;
 }
Beispiel #34
0
        private void btnIDGo_Click(object sender, EventArgs e)
        {
            gridUpdate = dataGridUpdate;
            formatGrid();

            // Check for invalid inputs
            if (textBoxDesiredTID.Text == "")
            {
                textBoxDesiredTID.Focus();
                return;
            }
            DesiredID = uint.Parse(textBoxDesiredTID.Text);

            if ((DesiredID > 65535) || (DesiredID < 0))
            {
                MessageBox.Show("Trainer ID must be between 0 and 65535.");
                textBoxDesiredTID.Focus();
                return;
            }

            if (cbxSearchSID.Checked)
            {
                if (textBoxDesiredSID.Text == "")
                {
                    textBoxDesiredSID.Focus();
                    return;
                }
                DesiredSID = uint.Parse(textBoxDesiredSID.Text);

                if ((DesiredSID > 65535) || (DesiredSID < 0))
                {
                    MessageBox.Show("Secret ID must be between 0 and 65535.");
                    textBoxDesiredSID.Focus();
                    return;
                }
            }

            if (textBoxIDMinDelay.Text == "")
            {
                MessageBox.Show("A recommended minimum delay value is 5000.");
                textBoxIDMinDelay.Focus();
                return;
            }
            MinDelay = uint.Parse(textBoxIDMinDelay.Text);

            if (!cbxIDInf.Checked)
            {
                Year = uint.Parse(textBoxIDYear.Text);
                if (Year < 2000 || Year > 2099)
                {
                    MessageBox.Show("Year must be between 2000 and 2099, inclusive.");
                    textBoxIDYear.Focus();
                    return;
                }

                Year = Year - 2000;

                if (textBoxIDMaxDelay.Text == "")
                {
                    textBoxIDMaxDelay.Focus();
                    return;
                }
                MaxDelay = uint.Parse(textBoxIDMaxDelay.Text);

                if (MaxDelay < MinDelay)
                {
                    MessageBox.Show("Max delay must be greater than or equal to min delay.");
                    textBoxIDMaxDelay.Focus();
                    return;
                }
            }

            btnShinyGo.Enabled = false;
            btnIDGo.Enabled = false;
            btnSeedGo.Enabled = false;
            btnSimpleGo.Enabled = false;
            btnIDCancel.Enabled = true;

            binding = new BindingSource();
            resultsList = new List<IDList>();
            binding.DataSource = resultsList;
            dgvResults.DataSource = binding;
            dt.Rows.Clear();

            if (!cbxIDInf.Checked)
            {
                // IDSearch
                bgwID.RunWorkerAsync();
            }
            else
            {
                // IDInfSearch
                bgwIDInf.RunWorkerAsync();
            }

            contextMenuStrip.Enabled = true;
        }
Beispiel #35
0
        private void btnSeedGo_Click(object sender, EventArgs e)
        {
            gridUpdate = dataGridUpdate;
            formatGrid();

            btnShinyGo.Enabled = false;
            btnIDGo.Enabled = false;
            btnSeedGo.Enabled = false;
            btnSimpleGo.Enabled = false;
            ErrorNo = 0;
            ErrorMsg = "";
            if (((!IsNumeric(txtSeedYr.Text))
                 || ((!IsNumeric(txtSeedMinDelay.Text))
                     || ((!IsNumeric(txtSeedMaxDelay.Text))
                         || ((!IsNumeric(txtIDObtained.Text))
                             || ((!IsNumeric(txtMonth.Text))
                                 || ((!IsNumeric(txtDay.Text))
                                     || ((!IsNumeric(txtHour.Text))
                                         || (!IsNumeric(txtMinute.Text))))))))))
            {
                ErrorMsg = "At least one of the required fields does not contain a number";
                ErrorNo = (ErrorNo + 1);
            }
            else
            {
                Year = uint.Parse(txtSeedYr.Text);

                if (((Year < 2000)
                     || (Year > 2099)))
                {
                    ErrorMsg = "Invalid Year (2000 <= Year <= 2099)";
                    ErrorNo = (ErrorNo + 1);
                }

                IDObtained = uint.Parse(txtIDObtained.Text);
                if (((IDObtained > 65535)
                     || (IDObtained < 0)))
                {
                    if ((ErrorNo > 0))
                    {
                        ErrorMsg = (ErrorMsg + '\r');
                    }
                    ErrorMsg = (ErrorMsg + "Invalid Trainer ID (0 <= ID <= 65535)");
                    ErrorNo = (ErrorNo + 1);
                }
                Month = uint.Parse(txtMonth.Text);
                if (((Month > 12)
                     || (Month < 1)))
                {
                    if ((ErrorNo > 0))
                    {
                        ErrorMsg = (ErrorMsg + '\r');
                    }
                    ErrorMsg = (ErrorMsg + "Invalid Month (1 <= Month <= 12)");
                    ErrorNo = (ErrorNo + 1);
                }
                Day = uint.Parse(txtDay.Text);
                if (((Day > 31)
                     || ((Day < 1)
                         || ((((Month == 4)
                               || ((Month == 6)
                                   || ((Month == 9)
                                       || (Month == 11))))
                              && (Day > 30))
                             || (((Month == 2)
                                  && (Day > 29))
                                 || ((Month == 2)
                                     && (((Year%4)
                                          != 0)
                                         && (Day > 28))))))))
                {
                    if ((ErrorNo > 0))
                    {
                        ErrorMsg = (ErrorMsg + '\r');
                    }
                    ErrorMsg = (ErrorMsg + "Invalid Day");
                    ErrorNo = (ErrorNo + 1);
                }
                Hour = uint.Parse(txtHour.Text);
                if (((Hour > 23)
                     || (Hour < 0)))
                {
                    if ((ErrorNo > 0))
                    {
                        ErrorMsg = (ErrorMsg + '\r');
                    }
                    ErrorMsg = (ErrorMsg + "Invalid Hour (0 <= Hour <= 23)");
                    ErrorNo = (ErrorNo + 1);
                }
                Minute = uint.Parse(txtMinute.Text);
                if (((Minute > 59)
                     || (Minute < 0)))
                {
                    if ((ErrorNo > 0))
                    {
                        ErrorMsg = (ErrorMsg + '\r');
                    }
                    ErrorMsg = (ErrorMsg + "Invalid Minute (0 <= Minute <= 59)");
                    ErrorNo = (ErrorNo + 1);
                }
            }
            if ((ErrorNo > 0))
            {
                MessageBox.Show(ErrorMsg, "Error(s) Occurred");
            }
            else
            {
                MinDelay = uint.Parse(txtSeedMinDelay.Text);
                MaxDelay = uint.Parse(txtSeedMaxDelay.Text);
                if ((MinDelay <= MaxDelay))
                {
                    MinDelay = uint.Parse(txtSeedMinDelay.Text);
                    MaxDelay = uint.Parse(txtSeedMaxDelay.Text);
                }
                else
                {
                    MaxDelay = uint.Parse(txtSeedMinDelay.Text);
                    MinDelay = uint.Parse(txtSeedMaxDelay.Text);
                }
                SeedsFound = 0;
                lblAction.Text = ("Searching for Obtained ID Seeds... Seeds Found: " + SeedsFound);

                // Set up DataTable for this operation
                binding = new BindingSource();
                resultsList = new List<IDList>();
                binding.DataSource = resultsList;
                dgvResults.DataSource = binding;
                dt.Rows.Clear();

                // Loop through viable seeds [AABBCCCC] for min and max delays
                // [AA] includes Month/Day/Minute/Seconds, [BB] includes Hours, and [CCCC] includes Year/Delay
                // First establish bounds of [CCCC] based on user input

                CCCCMin = ((Year - 2000) + MinDelay);
                CCCCMax = ((Year - 2000) + MaxDelay);

                SeedBB = Hour;
                for (Second = 0; (Second <= 59); Second++)
                {
                    for (SeedCCCC = CCCCMin; (SeedCCCC <= CCCCMax); SeedCCCC++)
                    {
                        // Establish seed
                        SeedAA = (((Month*Day)
                                   + (Minute + Second))
                                  %256);
                        Seed = (SeedCCCC
                                + ((65536*SeedBB) + (16777216*SeedAA)));
                        // Initialize Mersenne Twister (or IRNG) with new seed
                        a = new MersenneTwister(Seed);

                        // Call MT twice
                        y = a.Nextuint();
                        y = a.Nextuint();
                        TrainerID = (y & 0xFFFF);
                        SecretID = y >> 16;
                        if ((TrainerID == IDObtained))
                        {
                            Delay = (SeedCCCC + (2000 - Year));
                            SeedsFound = (SeedsFound + 1);
                            resultsList.Add(new IDList(Seed, Delay, TrainerID, SecretID, Second));
                            lblAction.Text = ("Searching for Obtained ID Seeds... Seeds Found: " + SeedsFound);
                        }
                    }
                }
                lblAction.Text = ("Desired Obtained Seed Search Completed! Seeds Found: " + SeedsFound);
                Invoke(gridUpdate);
            }
            btnShinyGo.Enabled = true;
            btnIDGo.Enabled = true;
            btnSeedGo.Enabled = true;
            btnSimpleGo.Enabled = true;

            contextMenuStrip.Enabled = true;
        }
Beispiel #36
0
        private void updateGUI()
        {
            gridUpdate = dataGridUpdate;
            ThreadDelegate resizeGrid = dgvResults.AutoResizeColumns;
            try
            {
                bool alive = true;
                while (alive)
                {
                    if (refresh)
                    {
                        Invoke(gridUpdate);
                        refresh = false;
                    }
                    if (searchThread == null || !searchThread.IsAlive)
                    {
                        alive = false;
                    }

                    Thread.Sleep(500);
                }
            }
            finally
            {
                Invoke(gridUpdate);
                Invoke(resizeGrid);
            }
        }
Beispiel #37
0
 public void Start(ThreadDelegate method) { method.DynamicInvoke(); }
Beispiel #38
0
        private void btnShinyGo_Click(object sender, EventArgs e)
        {
            gridUpdate = dataGridUpdate;
            formatGrid();

            // Check for invalid inputs
            if (textBoxShinyPID.Text == "")
            {
                textBoxShinyPID.Focus();
                return;
            }
            PID = Convert.ToUInt32(textBoxShinyPID.Text, 16);

            if (txtShinyMinDelay.Text == "")
            {
                MessageBox.Show("A recommended minimum delay value is 5000.");
                txtShinyMinDelay.Focus();
                return;
            }
            MinDelay = uint.Parse(txtShinyMinDelay.Text);

            if (!cbxShinyInf.Checked)
            {
                Year = uint.Parse(textBoxShinyYear.Text);
                if (Year < 2000 || Year > 2099)
                {
                    MessageBox.Show("Year must be between 2000 and 2099, inclusive.");
                    textBoxShinyYear.Focus();
                    return;
                }

                if (txtShinyMaxDelay.Text == "")
                {
                    txtShinyMaxDelay.Focus();
                    return;
                }
                MaxDelay = uint.Parse(txtShinyMaxDelay.Text);
            }

            if (cbxSearchID.Checked)
            {
                if (!uint.TryParse(textBoxShinyTID.Text, out DesiredID) || DesiredID > 65535)
                {
                    MessageBox.Show("Trainer ID must be a value betwwen 0 and 65535, inclusive.");
                    textBoxShinyTID.Focus();
                    return;
                }
            }

            binding = new BindingSource();
            resultsList = new List<IDList>();
            binding.DataSource = resultsList;
            dgvResults.DataSource = binding;

            btnShinyGo.Enabled = false;
            btnIDGo.Enabled = false;
            btnSeedGo.Enabled = false;
            btnSimpleGo.Enabled = false;
            btnShinyCancel.Enabled = true;

            if (!cbxShinyInf.Checked)
            {
                bgwShiny.RunWorkerAsync();
            }
            else
            {
                bgwShinyInf.RunWorkerAsync();
            }
        }
Beispiel #39
0
 // Instructs the ThreadPool class to run the given Jibu task with the given priority and 
 // synchronizing on the provided barrier.
 internal static void runTask(ThreadDelegate task, ThreadPriority priority)
 {
     JibuThread thread = JibuThreadPool.getThread();
     thread.setPriority(priority);
     thread.Task = task;
     thread.runThread();            
 }
Beispiel #40
0
Datei: Sdl.cs Projekt: vhotur/tao
 public static extern IntPtr SDL_CreateThread(ThreadDelegate fn, object data);
Beispiel #41
0
 internal static void runTask(ThreadDelegate task)
 {
     runTask(task, ThreadPriority.Normal);
 }
Beispiel #42
0
 public void Start(ThreadDelegate method) { }
Beispiel #43
0
 internal static void runTask(ThreadDelegate task)
 {
     runTask(task, ThreadPriority.Normal);
 }
Beispiel #44
0
 /// <summary>
 /// Thread function to collect the wmi data from machine.
 /// </summary>
 /// <param name="hostName">name of the machine</param>
 public void ScanMachine(string hostName)
 {
     _logger.Info("retrieve the wmi data from machine "+hostName);
     ThreadDelegate cb2 = new ThreadDelegate(CollectWMIData);
     object[]args={hostName};
     tp1.PostRequest(cb2, args);
 }