상속: Component
예제 #1
1
 public static void ParseRecommends(string html, Action<List<Recommend>> finished)
 {
     BackgroundWorker bw = new BackgroundWorker();
     bw.DoWork += new DoWorkEventHandler((sender, e) =>
     {
         List<Recommend> allRecommends = new List<Recommend>();
         HtmlDocument hDoc = new HtmlDocument();
         hDoc.LoadHtml(html);
         var tableRows = hDoc.DocumentNode.SelectNodes(Constants.Instance.XPATH_GAME_SHOW_RESULT);
         foreach (var node in tableRows)
         {
             var results = ChildElementsInTableRow(node);
             if (results.Count == Constants.Instance.COUNT_GAME_SHOW_RESULT_COLUMNS)
             {
                 var rec = RecommendFromStrings(results);
                 if (IsValidRecommend(rec))
                 {
                     allRecommends.Add(rec);
                 }
             }
         }
         finished(allRecommends);
     });
     bw.RunWorkerAsync();
 }
예제 #2
1
        private IEnumerable<XElement> AddDirectoryAsync(DirectoryInfo dir, string collectionId, ref int count, int fnumber,
            BackgroundWorker worker)
        {
            List<XElement> addedElements = new List<XElement>();
            // добавление коллекции
            string subCollectionId;
            List<XElement> ae = this.cass.AddCollection(dir.Name, collectionId, out subCollectionId).ToList();
            if (ae.Count > 0) addedElements.AddRange(ae);

            count++;
            foreach (FileInfo f in dir.GetFiles())
            {
                if (worker.CancellationPending) break;
                if (f.Name != "Thumbs.db")
                    addedElements.AddRange(this.cass.AddFile(f, subCollectionId));
                count++;
                worker.ReportProgress(100 * count / fnumber);
            }
            foreach (DirectoryInfo d in dir.GetDirectories())
            {
                if (worker.CancellationPending) break;
                addedElements.AddRange(AddDirectoryAsync(d, subCollectionId, ref count, fnumber, worker));
            }
            return addedElements;
        }
예제 #3
1
 public static void ParseTopPerson(string html, Action<List<Person>> finished)
 {
     BackgroundWorker bw = new BackgroundWorker();
     bw.DoWork += new DoWorkEventHandler((sender, e) =>
     {
         List<Person> TopPerson = new List<Person>();
         HtmlDocument hDoc = new HtmlDocument();
         hDoc.LoadHtml(html);
         var tableRows = hDoc.DocumentNode.SelectNodes(Constants.Instance.XPATH_GAME_TOP_RESULT);
         foreach (var node in tableRows)
         {
             var results = ChildElementsInTableRow(node);
             if (results.Count == Constants.Instance.COUNT_GAME_TOP_RESULT_COLUMNS)
             {
                 var person = TopPersonFromStrings(results);
                 if (person.Total != 0)
                 {
                     TopPerson.Add(person);
                 }
             }
         }
         finished(TopPerson);
     });
     bw.RunWorkerAsync();
 }
예제 #4
0
 public void CreateDictionaryHash()
 {
     var prefixTreeThread = new BackgroundWorker();
     prefixTreeThread.DoWork += ReadPrefixTree;
     prefixTreeThread.RunWorkerCompleted += ReadPrefixTreeComplete;
     prefixTreeThread.RunWorkerAsync();
 }
예제 #5
0
        public PlayGroundView()
        {
            InitializeComponent();


            this.presenter = Presenters.PlayGroundPresenter;
            presenter.InitWithView(this);

            txtJavaScriptCode.Language = FastColoredTextBoxNS.Language.JS;
            // https://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx
            this.runScriptBackgroundWorker         = new System.ComponentModel.BackgroundWorker();
            this.runScriptBackgroundWorker.DoWork +=
                new DoWorkEventHandler(runScriptBackgroundWorker_DoWork);
            // this.runScriptBackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorkerExample_ProgressChanged);
            this.runScriptBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(runScriptBackgroundWorker_RunWorkerCompleted);

            presenter.InitiCodeEditor();

            txtJavaScriptCode.Text =
                @"// WebDriver Playground enables you to operate the WebElements at runtime. 
// Go to any page and define any web element into PageObject tree on the right side. 
// For instance, you have declared a text field with name “txtLogin”. 
// Now you can write the following JavaScript to manipulate the web element: 
// 
//      txtLogin.Clear()
//      txtLogin.SendKeys(""Hello World"")
// 
// WebDriver Playground is in ALPHA quality. The following classes supported: 
// PageObject web elements, (IWebElement), driver (IWebDriver), By, Keys, Actions.

driver.Navigate().GoToUrl(""https://github.com/dzharii/swd-recorder"");
driver.GetScreenshot().SaveAsFile(""Screenshots\\mywebpagetest.png"", ImageFormat.Png); // See <SwdRecorder.exe-folder>\Screenshots
";
        }
예제 #6
0
 public BackgroundWorkerTask(BackgroundWorkerDelegate newFunction)
 {
     backgroundMethod = newFunction;
     Bw = new BackgroundWorker();
     Bw.DoWork += new DoWorkEventHandler(Bw_DoWork);
     Bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Bw_RunWorkerCompleted);
 }
예제 #7
0
 /// <summary>
 /// Initialize the manager, should be called in OnNavigatedTo of main page.
 /// </summary>
 public void Initialize()
 {
     socket = new StreamSocket();
     dataReadWorker = new BackgroundWorker();
     dataReadWorker.WorkerSupportsCancellation = true;
     dataReadWorker.DoWork += new DoWorkEventHandler(ReceiveMessages);
 }
예제 #8
0
        private void uiRecoverButton_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrWhiteSpace(path))
            {
                MessageBox.Show("Please select an extracted OSIRT case file", "No case path selected", MessageBoxButtons.OK,MessageBoxIcon.Warning);
                return;
            }

            if (!IsExtractedCase(path))
            {
                MessageBox.Show("This doesn't appear to be an extracted OSIRT case file. Directory is missing case.db file.", "Not extracted OSIRT case", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            FlipUi(true, "Recovering...");
            var backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += delegate
            {
                System.Threading.Thread.Sleep(1000);
                RezipCase(path);
              
            };
            backgroundWorker.RunWorkerCompleted += delegate
            {
                FlipUi(false, "Recover");
            };
            backgroundWorker.RunWorkerAsync();
        }
 public override void RefreshAllAsync()
 {
     BackgroundWorker refreshAllWorker = new BackgroundWorker();
     refreshAllWorker.DoWork += new DoWorkEventHandler(RefreshWorker_DoWork);
     refreshAllWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RefreshWorker_RunWorkerCompleted);
     refreshAllWorker.RunWorkerAsync();
 }
예제 #10
0
        private void b_open_Click(object sender_, RoutedEventArgs e_)
        {
            p_progress.Visibility = Visibility.Visible;
            p_label.Visibility = Visibility.Visible;

            bw_LoadFile = new BackgroundWorker();
            bw_LoadFile.DoWork += (sender, e) =>
            {
                LCIO.OpenFile(bw_LoadFile);
            };
            bw_LoadFile.ProgressChanged += (sender, e) =>
            {
                p_label.Content = e.UserState;
            };
            bw_LoadFile.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    new TextMessage("Ошибка", e.Error.Message).ShowDialog();
                }
                p_progress.Visibility = Visibility.Hidden;
                p_label.Visibility = Visibility.Hidden;
                FLYOUT_OpenFile.IsOpen = false;
                UpdateList();
            };
            bw_LoadFile.WorkerReportsProgress = true;
            bw_LoadFile.RunWorkerAsync();
        }
        public frmLevelScene(string filename, string depotPath, Cache.TextureManager textureManager)
        {
            this.inputFilename = filename;
            this.depot         = depotPath + "\\";
            this.meshId        = 1;
            InitializeComponent();

            this.showAllButton.Enabled = false;
            this.addMeshButton.Enabled = false;

            this.progressBar.Minimum = 0;
            this.progressBar.Maximum = 10;
            this.progressBar.Value   = 0;
            this.progressBar.Step    = 1;

            this.queueSizeBar.Minimum = 0;
            this.queueSizeBar.Maximum = 5000;
            this.queueSizeBar.Value   = 0;
            this.queueSizeBar.Step    = 1;

            this.distanceBar.Value = 3;

            this.rotateModeBtn.Enabled    = false;
            this.translateModeBtn.Enabled = false;

            this.propertiesDlg = new MeshPropertyDialog();

            this.backgroundLoader                     = new System.ComponentModel.BackgroundWorker();
            this.backgroundLoader.DoWork             += new DoWorkEventHandler(LoadScene);
            this.backgroundLoader.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SceneLoaded);

            this.backgroundSearcher                     = new System.ComponentModel.BackgroundWorker();
            this.backgroundSearcher.DoWork             += new DoWorkEventHandler(FindSceneNode);
            this.backgroundSearcher.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SceneNodeFound);
        }
        public CAanalysisDetails(int iType, DateTime dteStartDate, DateTime DteEndDate, int iWeekID)
        {
            InitializeComponent();
            try
            {
                _dteStartDate = dteStartDate;
                _DteEndDate   = DteEndDate;
                if (iType == -99)
                {
                    lblStatus.Visibility    = Visibility.Visible;
                    progressBar1.Visibility = Visibility.Visible;
                    //txtHeader.Text = "Drop Week BreakDown";
                    txtHeader1.Visibility = Visibility.Visible;
                    txtHeader.Visibility  = Visibility.Hidden;
                    btnPrint.Visibility   = Visibility.Hidden;
                    btnExport.Visibility  = Visibility.Hidden;
                    btnRefresh.Visibility = Visibility.Hidden;

                    _iType   = -99;
                    _iWeekID = iWeekID;

                    backgroundWorker1                     = new BackgroundWorker();
                    backgroundWorker1.DoWork             += new DoWorkEventHandler(backgroundWorker1_DoWork);
                    backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
                }
                else
                {
                    Refresh(iType, dteStartDate, DteEndDate);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Publish(ex);
            }
        }
        /// <summary>
        /// Method to run a single command
        /// </summary>
        /// <param name="commandText">Command to run</param>
        internal void RunCommand(string pCommandText)
        {
            try
            {
                if (!String.IsNullOrEmpty(pCommandText))
                {
                    this.commandText = pCommandText.Trim();

                    this.CurrentBackGroundWorker = new System.ComponentModel.BackgroundWorker();
                    this.CurrentBackGroundWorker.WorkerSupportsCancellation = true;
                    this.CurrentBackGroundWorker.DoWork             += new System.ComponentModel.DoWorkEventHandler(worker_DoWork);
                    this.CurrentBackGroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

                    this.CurrentBackGroundWorker.RunWorkerAsync();
                }
            }
            catch (ParseException args)
            {
                string message = string.Format(
                    "Parse error caused by token: {0}",
                    args.UnexpectedToken.Text);
                this.programEditor.ShowErrorMessage(message);
                this.programEditor.SetCursor(args);
            }
            catch (Exception ex)
            {
                this.programEditor.ShowErrorMessage(ex.ToString());
            }
        }
예제 #14
0
 public GuiWithTools()
 {
     this.backgroundWorkerSplitPdf  = new System.ComponentModel.BackgroundWorker();
     this.backgroundWorkerMergeTiff = new System.ComponentModel.BackgroundWorker();
     this.backgroundWorkerMergePdf  = new System.ComponentModel.BackgroundWorker();
     this.backgroundWorkerSplitTiff = new System.ComponentModel.BackgroundWorker();
     //
     // backgroundWorkerSplitPdf
     //
     this.backgroundWorkerSplitPdf.DoWork             += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorkerSplitPdf_DoWork);
     this.backgroundWorkerSplitPdf.ProgressChanged    += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorkerSplitPdf_ProgressChanged);
     this.backgroundWorkerSplitPdf.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorkerSplitPdf_RunWorkerCompleted);
     //
     // backgroundWorkerMergeTiff
     //
     this.backgroundWorkerMergeTiff.DoWork             += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorkerMergeTiff_DoWork);
     this.backgroundWorkerMergeTiff.ProgressChanged    += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorkerMergeTiff_ProgressChanged);
     this.backgroundWorkerMergeTiff.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorkerMergeTiff_RunWorkerCompleted);
     //
     // backgroundWorkerMergePdf
     //
     this.backgroundWorkerMergePdf.DoWork             += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorkerMergePdf_DoWork);
     this.backgroundWorkerMergePdf.ProgressChanged    += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorkerMergePdf_ProgressChanged);
     this.backgroundWorkerMergePdf.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorkerMergePdf_RunWorkerCompleted);
     //
     // backgroundWorkerSplitTiff
     //
     this.backgroundWorkerSplitTiff.DoWork             += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorkerSplitTiff_DoWork);
     this.backgroundWorkerSplitTiff.ProgressChanged    += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorkerSplitTiff_ProgressChanged);
     this.backgroundWorkerSplitTiff.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorkerSplitTiff_RunWorkerCompleted);
 }
예제 #15
0
 /// <summary>
 /// 设置textbox智能提示输入框
 /// </summary>
 private void Intelligence()
 {
     /*设置自动完成属性*/
     this.tbAccount.AutoCompleteMode   = AutoCompleteMode.SuggestAppend;
     this.tbAccount.AutoCompleteSource = AutoCompleteSource.CustomSource;
     /*ac集合进行初始化*/
     if (ac == null)
     {
         ac = new AutoCompleteStringCollection();
         Users user = this.GetUserList();
         if (user == null)
         {
             return;
         }
         else
         {
             foreach (string name in user.UserName)
             {
                 this.ac.Add(name);
             }
         }
     }
     /*background 事件*/
     if (bw == null)
     {
         bw = new BackgroundWorker();
     }
     bw.RunWorkerAsync();//异步调用
     this.bw.DoWork             += new DoWorkEventHandler(delegate(object sender, DoWorkEventArgs e) { e.Result = ac; });
     this.bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object sender, RunWorkerCompletedEventArgs e)
     {
         this.tbAccount.AutoCompleteCustomSource = (AutoCompleteStringCollection)e.Result;
     });
 }
예제 #16
0
        private void RunPSATransfer(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            System.ComponentModel.BackgroundWorker           worker             = sender as System.ComponentModel.BackgroundWorker;
            YellowstonePathology.Business.ReportNoCollection reportNoCollection = YellowstonePathology.Business.Gateway.AccessionOrderGateway.GetReportNumbersByPostDate(this.m_PostDate.Value);

            string workingFolder = System.IO.Path.Combine(this.m_BaseWorkingFolderPath, this.m_PostDate.Value.ToString("MMddyyyy"));

            this.SetupWorkingFolders(workingFolder);

            foreach (YellowstonePathology.Business.ReportNo reportNo in reportNoCollection)
            {
                string masterAccessionNo = YellowstonePathology.Business.Gateway.AccessionOrderGateway.GetMasterAccessionNoFromReportNo(reportNo.Value);
                YellowstonePathology.Business.Test.AccessionOrder accessionOrder = YellowstonePathology.Business.Persistence.DocumentGateway.Instance.GetAccessionOrderByMasterAccessionNo(masterAccessionNo);
                YellowstonePathology.Business.Test.PanelSetOrder  panelSetOrder  = accessionOrder.PanelSetOrderCollection.GetPanelSetOrder(reportNo.Value);

                if (accessionOrder.UseBillingAgent == true)
                {
                    if (panelSetOrder.IsBillable == true)
                    {
                        if (panelSetOrder.PanelSetOrderCPTCodeBillCollection.HasItemsToSendToPSA() == true)
                        {
                            this.m_ReportNumbersToProcess.Add(reportNo.Value);
                            this.CreatePatientTifFile(reportNo.Value);
                            this.CreateXmlBillingDocument(accessionOrder, reportNo.Value);
                            this.CopyFiles(reportNo.Value, accessionOrder.MasterAccessionNo, workingFolder);

                            this.m_BackgroundWorker.ReportProgress(1, reportNo.Value + " Complete.");
                        }
                    }
                }
            }
        }
        public EgsDeviceFaceDetectionOnHost()
        {
            // +X:Right  +Y:Bottom  +Z:Back (camera to user)

            // Parameters input by user
            // 3[m].  10 feet UI
            MaxDetectableDistanceInMeter = new RangedDouble(3.0, 1.0, 5.0, 0.1, 0.5, 0.1);
            // (120,200) Avg: M:162 F:156  But the actual recognition result breadth is smaller than this definition.
            RealFaceBreadth = new RangedDouble(159, 120, 200, 1, 5, 1);
            // ( 65, 95) Avg: M: 82 F: 74
            RealPalmBreadth = new RangedDouble(78, 65, 95, 1, 3, 1);

            IsToUpdateRealHandDetectionAreaFromBodyParameters = true;
            // (310,440) Avg: M:397 F:361
            RealShoulderBreadth = new RangedDouble(379, 310, 440, 1, 10, 1);
            RealHandDetectionAreaCenterXOffset_DividedBy_RealShoulderBreadth = new RangedDouble(0.68, 0, 1, 0.01, 0.1, 0.01);
            RealHandDetectionAreaCenterYOffset_DividedBy_RealFaceBreadth     = new RangedDouble(0.63, 0, 2, 0.01, 0.1, 0.01);
            RealHandDetectionAreaCenterZOffset_DividedBy_RealShoulderBreadth = new RangedDouble(-0.26, -1, 0, 0.01, 0.1, 0.01);
            RealHandDetectionAreaWidth_DividedBy_RealPalmBreadth             = new RangedDouble(4.5, 3, 6, 0.1, 1.0, 0.1);
            RealHandDetectionAreaHeight_DividedBy_RealPalmBreadth            = new RangedDouble(5.1, 3, 6, 0.1, 1.0, 0.1);

            RealHandDetectionAreaCenterXOffset = new RangedDouble(RealHandDetectionAreaCenterXOffset_DividedBy_RealShoulderBreadth * RealShoulderBreadth, 0, 500, 10, 50, 10);
            RealHandDetectionAreaCenterYOffset = new RangedDouble(RealHandDetectionAreaCenterYOffset_DividedBy_RealFaceBreadth * RealFaceBreadth, -100, 200, 10, 50, 10);
            RealHandDetectionAreaCenterZOffset = new RangedDouble(RealHandDetectionAreaCenterZOffset_DividedBy_RealShoulderBreadth * RealShoulderBreadth, -300, 0, 10, 50, 10);
            RealHandDetectionAreaWidth         = new RangedDouble(RealHandDetectionAreaWidth_DividedBy_RealPalmBreadth * RealPalmBreadth, 100, 500, 10, 50, 10);
            RealHandDetectionAreaHeight        = new RangedDouble(RealHandDetectionAreaHeight_DividedBy_RealPalmBreadth * RealPalmBreadth, 100, 500, 10, 50, 10);

            RealFaceCenterZ = double.PositiveInfinity;

            SensitivityAndSpecificity = new RangedInt(0, -3, 3, 1, 1, 1);

            DetectFaceIntervalMillisecondsMinimum = new RangedInt(200, 0, 2000, 10, 100, 10);
            DetectFaceIntervalMinimumStopwatch    = Stopwatch.StartNew();
            Worker         = new System.ComponentModel.BackgroundWorker();
            Worker.DoWork += delegate
            {
                DetectFaces();
            };
            Worker.RunWorkerCompleted += delegate
            {
                DetectFaces_RunWorkerCompleted();
            };
            IsDetecting = false;

            DlibArray2dUcharImage     = new DlibSharp.Array2dUchar();
            DlibHogSvm                = new DlibSharp.FrontalFaceDetector();
            DetectionElapsedStopwatch = new Stopwatch();

            IsToUpdateRealHandDetectionAreaFromBodyParametersChanged += delegate { UpdateRealHandDetectionAreaParametersFromRealBodyParameters(); };
            RealFaceBreadth.ValueChanged     += delegate { UpdateRealHandDetectionAreaParametersFromRealBodyParameters(); };
            RealPalmBreadth.ValueChanged     += delegate { UpdateRealHandDetectionAreaParametersFromRealBodyParameters(); };
            RealShoulderBreadth.ValueChanged += delegate { UpdateRealHandDetectionAreaParametersFromRealBodyParameters(); };
            RealHandDetectionAreaCenterXOffset_DividedBy_RealShoulderBreadth.ValueChanged += delegate { UpdateRealHandDetectionAreaParametersFromRealBodyParameters(); };
            RealHandDetectionAreaCenterYOffset_DividedBy_RealFaceBreadth.ValueChanged     += delegate { UpdateRealHandDetectionAreaParametersFromRealBodyParameters(); };
            RealHandDetectionAreaCenterZOffset_DividedBy_RealShoulderBreadth.ValueChanged += delegate { UpdateRealHandDetectionAreaParametersFromRealBodyParameters(); };
            RealHandDetectionAreaWidth_DividedBy_RealPalmBreadth.ValueChanged             += delegate { UpdateRealHandDetectionAreaParametersFromRealBodyParameters(); };
            RealHandDetectionAreaHeight_DividedBy_RealPalmBreadth.ValueChanged            += delegate { UpdateRealHandDetectionAreaParametersFromRealBodyParameters(); };

            Reset();
        }
예제 #18
0
        public static void MakeDatZips(object sender, DoWorkEventArgs e)
        {
            _bgw = sender as BackgroundWorker;
            Program.SyncCont = e.Argument as SynchronizationContext;
            if (Program.SyncCont == null)
            {
                _bgw = null;
                return;
            }

            if (!Directory.Exists(_outputdir))
                return;

            if (_treeRow != null)
                FindDats(_treeRow);
            else
            {
                RvGame tGame = new RvGame();
                tGame.DBRead((int)_gameId, true);
                ExtractGame(tGame, _outputdir);
            }
            _bgw.ReportProgress(0, new bgwText("Creating Zips Complete"));
            _bgw = null;
            Program.SyncCont = null;
        }
예제 #19
0
        public Lobby(Menu parent)
        {
            InitializeComponent();

            ImageBrush myBrush = new ImageBrush();
            myBrush.ImageSource = new BitmapImage(new Uri(".\\Resources\\icon_backarrow.png", UriKind.Relative));
            bekk.Background = myBrush;

            ImageBrush myBrush2 = new ImageBrush();
            myBrush2.ImageSource = new BitmapImage(new Uri(".\\Resources\\icon_closebutton.png", UriKind.Relative));
            klóz.Background = myBrush2;

            this.parent = parent;

            chatbox.Items.Clear();

            refreshworker = new BackgroundWorker();
            refreshworker.WorkerSupportsCancellation = true;
            refreshworker.WorkerReportsProgress = true;
            refreshworker.DoWork += refresh;
            refreshworker.ProgressChanged += refreshUI;

            activityworker = new BackgroundWorker();
            activityworker.WorkerSupportsCancellation = true;
            activityworker.DoWork += wait;
            activityworker.RunWorkerCompleted += doActivity;
        }
예제 #20
0
        /// <summary>
        /// Loads the in background.
        /// </summary>
        private void LoadInBackground()
        {
            BackgroundWorker bgw = new System.ComponentModel.BackgroundWorker();

            bgw.DoWork += new DoWorkEventHandler(Load);
            bgw.RunWorkerAsync();
        }
예제 #21
0
        public Pomo()
        {
            worker                     = new BackgroundWorker();
            worker.DoWork             += WorkerDoWork;
            worker.RunWorkerCompleted += WorkerDone;

            InitializeComponent();

            this.Icon = BitmapFrame.Create(new Uri(@"tomato.png", UriKind.Relative));

            BtnStpWork.Visibility = Visibility.Hidden;

            notifyIcon      = new NotifyIcon();
            notifyIcon.Icon = new Icon(@"tomato.ico");

            ToolStripMenuItem tmiClose = new ToolStripMenuItem();

            tmiClose.Text   = "Close";
            tmiClose.Click += new System.EventHandler(TmiClose_Click);

            ToolStripMenuItem tmiShow = new ToolStripMenuItem();

            tmiShow.Text   = "Show";
            tmiShow.Click += TmiShow_Click;

            ContextMenuStrip contextMenuStrip = new ContextMenuStrip();

            contextMenuStrip.Items.Add(tmiShow);
            contextMenuStrip.Items.Add(tmiClose);

            notifyIcon.ContextMenuStrip = contextMenuStrip;
            notifyIcon.BalloonTipText   =
                Properties.Resources.Pomo_Tray_Stuff;
            notifyIcon.Visible = true;
        }
예제 #22
0
파일: Form1.cs 프로젝트: lixeon/NIIT-Source
        private double SumNumbers(double number, System.ComponentModel.BackgroundWorker worker, DoWorkEventArgs e)
        {
            int    lastPercent = 0;
            double sum = 0, i = 0;

            for (i = 0; i <= number; i++)
            {
                //---check if user cancelled the process
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                }
                else
                {
                    sum += i;
                    if (i % 10 == 0)
                    {
                        int percentDone = Convert.ToInt32((i / number) * 100);
                        //---update the progress bar if there is a change
                        if (percentDone > lastPercent)
                        {
                            //This method calls BackgroundWorker1_ProgressChanged method
                            worker.ReportProgress(percentDone);
                            lastPercent = percentDone;
                        }
                    }
                }
            }
            return(sum);
        }
        public CPromoCashableDetails(string RouteNumber, DateTime StartDate, DateTime EndDate,int UserNo)
        {
            InitializeComponent();
            _worker = new BackgroundWorker();
            _worker.WorkerReportsProgress = true;
            _worker.WorkerSupportsCancellation = true;

            CurrencySymbol = CurrencySymbol.GetCurrencySymbol();
            this.RouteNumber = RouteNumber;
            this.StartDate = StartDate;
            this.EndDate = EndDate;
            this.UserNo = UserNo;

            // For resizing columns automatically.
            GridView gv = lvPromoCashable.View as GridView;
            if (gv != null)
            {
                foreach (GridViewColumn gvc in gv.Columns)
                {
                    gvc.Width = gvc.ActualWidth;
                    if (gvc.Width == 0.0 || gvc.Width == 0)
                        gvc.Width = 0;
                    else
                        gvc.Width = Double.NaN;
                }
            }        
        }
예제 #24
0
        public async Task init()
        {
            MyCalculateHash = new SprightlySoftAWS.S3.CalculateHash();
            //yCalculateHash.ProgressChangedEvent += MyCalculateHash_ProgressChangedEvent;

            MyUpload = new SprightlySoftAWS.S3.Upload();
            //MyUpload.ProgressChangedEvent += MyUpload_ProgressChangedEvent;

            CalculateHashBackgroundWorker                     = new System.ComponentModel.BackgroundWorker();
            CalculateHashBackgroundWorker.DoWork             += CalculateHashBackgroundWorker_DoWork;
            CalculateHashBackgroundWorker.RunWorkerCompleted += CalculateHashBackgroundWorker_RunWorkerCompleted;

            UploadBackgroundWorker                     = new System.ComponentModel.BackgroundWorker();
            UploadBackgroundWorker.DoWork             += UploadBackgroundWorker_DoWork;
            UploadBackgroundWorker.RunWorkerCompleted += UploadBackgroundWorker_RunWorkerCompleted;
            //Application.DoEvents();
            StreamWriter SW = new StreamWriter(HttpContext.Server.MapPath("../") + "init.txt");

            SW.WriteLine("public void init()");
            SW.Close();
            //Run the hash calculation in a BackgroundWorker process.  Calculating the hash of a
            //large file will take a while.  Running the process in a BackgroundWorker will prevent
            //the form from locking up.

            //Use a hash table to pass parameters to the function in the BackgroundWorker.
            Task task = new Task(ProcessDataAsync);

            task.Start();
            task.Wait();
        }
예제 #25
0
        public bool dooptimization()
        {
            initialcount = points.Count;
            currentpoint = 0;
            finishedthreads = 0;
            bws = new List<BackgroundWorker>();
            for(int i=0;i<100;i++)
            {
                bws.Add(new BackgroundWorker());
                            bws[i] = new BackgroundWorker
                {
                    WorkerReportsProgress = true,
                    WorkerSupportsCancellation = true
                };
                bws[i].DoWork += bw_DoWork;

                bws[i].RunWorkerCompleted += bw_RunWorkerCompleted;
                bws[i].RunWorkerAsync();//pass id???, what else?

            }
            while (finishedthreads!=100)
            {

            }
                return true;
        }
예제 #26
0
        /// <summary>
        /// Override of <see cref="ApplicationComponent.Start"/>
        /// </summary>
        /// <remarks>
        /// For internal Framework use only.
        /// </remarks>
        public override void Start()
        {
            base.Start();

            _uiThreadSynchronizationContext = SynchronizationContext.Current;

            _contextMenuFilter = _setupHelper.GetContextMenuFilter() ?? ViewerActionFilter.Null;
            _contextMenuFilter.SetImageViewer(this);

            _toolbarFilter = _setupHelper.GetToolbarFilter() ?? ViewerActionFilter.Null;
            _toolbarFilter.SetImageViewer(this);

            _toolSet = new ToolSet(CreateTools(), CreateToolContext());

            // since the keyboard action model is otherwise never used, we explicitly invoke it here to apply the persisted action model values to the actions
            ActionModelRoot.CreateModel(ActionsNamespace, KeyboardSite, _toolSet.Actions);

            foreach (ITool tool in _toolSet.Tools)
            {
                _shortcutManager.RegisterImageViewerTool(tool);
            }

            this.backgroundWorker = new BackgroundWorker();
            this.backgroundWorker.WorkerSupportsCancellation = true;
            this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_DoWork);
        }
        public Form1()
        {
            InitializeComponent();
            this.pictureBox1.Paint += new PaintEventHandler(pictureBox1_Paint);
            this.MouseDown         += new MouseEventHandler(Form1_MouseDown);

            initialHelperList();

            this.cmbProductName.Items.Clear();
            this.cmbProductName.Items.Add("无");
            this.cmbProductName.SelectedIndex = 0;

            this.cmbCarbinetIndex.Items.Add("货架一");
            this.cmbCarbinetIndex.Items.Add("货架二");
            //this.cmbCarbinetIndex.Items.Add("货架三");
            //this.cmbCarbinetIndex.Items.Add("货架四");
            this.cmbCarbinetIndex.SelectedIndex = 0;

            this.FormClosing += new FormClosingEventHandler(SGSserverForm_FormClosing);
            this.Shown       += new EventHandler(Form1_Shown);


            //this.lblLocation.Text = string.Format("hp = {0} wp = {1}", staticClass.heightPara, staticClass.widthPara);
            this.lblStatus.Text = "";

            backgroundWorker1         = new System.ComponentModel.BackgroundWorker();
            backgroundWorker1.DoWork +=
                new DoWorkEventHandler(backgroundWorker1_DoWork);
            //this.helper.listener = this;
        }
예제 #28
0
 public ImageAnalyzerO()
 {
     bwImageAnalizer                     = new BackgroundWorker();
     bwImageAnalizer.DoWork             += bwImageAnalizer_DoWork;
     bwImageAnalizer.RunWorkerCompleted += bwImageAnalizer_RunWorkerCompleted;
     bwImageAnalizer.ProgressChanged    += bwImageAnalizer_ProgressChanged;
 }
예제 #29
0
 private static void UpdateCheck()
 {
     Game.PrintChat("<font color='#33FFFF'> .: Orianna by trelli loaded :.");
     var bgw = new BackgroundWorker();
     bgw.DoWork += bgw_DoWork;
     bgw.RunWorkerAsync();
 }
예제 #30
0
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                button1.Enabled      = false;
                button_flash.Enabled = false;
                busy = true;

                ih = new IntelHex();
                //ih.loadhex(ofd.FileName);

                textBox1.AppendText("** Loading hex file **\r\n");

                filename = ofd.FileName;
                node     = (byte)numericUpDown_node.Value;

                backgroundWorker1 = new BackgroundWorker();

                backgroundWorker1.DoWork +=
                    new DoWorkEventHandler(backgroundWorker1_DoWork);

                backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;

                backgroundWorker1.RunWorkerAsync();
            }
        }
예제 #31
0
    public PluginUpdaterForm(PluginManager pluginManager)
      : base() {
      InitializeComponent();
      Text = "HeuristicLab Plugin Manager " + AssemblyHelpers.GetFileVersion(GetType().Assembly);
      pluginManager.PluginLoaded += pluginManager_PluginLoaded;
      pluginManager.PluginUnloaded += pluginManager_PluginUnloaded;
      pluginManager.Initializing += pluginManager_Initializing;
      pluginManager.Initialized += pluginManager_Initialized;

      pluginDir = Application.StartupPath;

      installationManager = new InstallationManager(pluginDir);
      installationManager.PluginInstalled += new EventHandler<PluginInfrastructureEventArgs>(installationManager_PluginInstalled);
      installationManager.PluginRemoved += new EventHandler<PluginInfrastructureEventArgs>(installationManager_PluginRemoved);
      installationManager.PluginUpdated += new EventHandler<PluginInfrastructureEventArgs>(installationManager_PluginUpdated);
      installationManager.PreInstallPlugin += new EventHandler<PluginInfrastructureCancelEventArgs>(installationManager_PreInstallPlugin);
      installationManager.PreRemovePlugin += new EventHandler<PluginInfrastructureCancelEventArgs>(installationManager_PreRemovePlugin);
      installationManager.PreUpdatePlugin += new EventHandler<PluginInfrastructureCancelEventArgs>(installationManager_PreUpdatePlugin);

      this.pluginManager = pluginManager;

      updatePluginsBackgroundWorker = new BackgroundWorker();
      updatePluginsBackgroundWorker.DoWork += new DoWorkEventHandler(updatePluginsBackgroundWorker_DoWork);
      updatePluginsBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(updatePluginsBackgroundWorker_RunWorkerCompleted);
    }
        public frmOSAIFileUtility()
        {
            InitializeComponent();
            //ToolTip objToolTip = new ToolTip();
            backgroundWorker1 = new System.ComponentModel.BackgroundWorker();


            //Adds my ToolTip
            //objToolTip.SetToolTip(txtHexToAddatEnd, "Type Hex Characters with NO spaces");
            //objToolTip.AutomaticDelay = 1000;

            //Registers my DoWork, ProgressChanged, and RunWorkerCompleted methods
            backgroundWorker1.DoWork             += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
            backgroundWorker1.ProgressChanged    += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
            backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);

            backgroundWorker1.WorkerReportsProgress      = true;
            backgroundWorker1.WorkerSupportsCancellation = true;

            dgvProgramFileList.DataSource = CommunicationManagerOSAI.ProgramFiles;

            BindingSource objBindingSource = new BindingSource();

            objBindingSource.DataSource = CommunicationManagerOSAI.ProgramFiles;
            findStrip1.BindingSource    = objBindingSource;
            findStrip1.LoadSearchProperties();
            //findStrip1.BindingSource = new BindingSource();
            //findStrip1.BindingSource.DataSource = CommunicationManagerOSAI.ProgramFiles;
        }
예제 #33
0
        public LoaderForm()
        {
            InitializeComponent();

            stage = Stage.UserInfo;

            // setting up the starting loader screen
            LabelOperationPercentage.Text = "0%";
            LabelOverallStage.Text        = "0/5";
            LabelOperation.Text           = "Contacting Facebook...";

            // setting up the worker thread
            backgroundLoader = new System.ComponentModel.BackgroundWorker();

            backgroundLoader.WorkerReportsProgress      = true;
            backgroundLoader.WorkerSupportsCancellation = true;

            backgroundLoader.DoWork             += new DoWorkEventHandler(backgroundLoader_DoWork);
            backgroundLoader.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundLoader_RunWorkerCompleted);
            backgroundLoader.ProgressChanged    += new ProgressChangedEventHandler(backgroundLoader_ProgressChanged);

            // starting the calculation
            // runs the GenerateGraph() method in Generator.cs
            backgroundLoader.RunWorkerAsync();
        }
예제 #34
0
        /* Downloads projects on a different thread to UI thread, so user can do other tasks while downloading. */
        private void downloadProject(string path, string PID)
        {
            BackgroundWorker backgroundWorker;

            // Instantiate BackgroundWorker and attach handlers to its
            // DowWork and RunWorkerCompleted events.
            backgroundWorker                     = new System.ComponentModel.BackgroundWorker();
            backgroundWorker.DoWork             += new System.ComponentModel.DoWorkEventHandler(backgroundWorker_DoWork);
            backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted);

            string[] parameters = new string[] { path, PID };

            prog = new ProgressBar();
            // Start the download operation in the background.
            backgroundWorker.RunWorkerAsync(parameters);

            // Once you have started the background thread you
            // can exit the handler and the application will
            // wait until the RunWorkerCompleted event is raised.

            // Or if you want to do something else in the main thread,
            // such as update a progress bar, you can do so in a loop
            // while checking IsBusy to see if the background task is
            // still running.

            while (backgroundWorker.IsBusy)
            {
                // Keep UI messages moving, so the form remains
                // responsive during the asynchronous operation.

                Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
                                                      new Action(delegate { }));
            }
        }
예제 #35
0
 private void button1_Click(object sender, EventArgs e)
 {
     BackgroundWorker worker = new BackgroundWorker();
     DataLocation loc = (DataLocation)ComboBoxSearchLocation.SelectedIndex;
     worker.DoWork += (s, args) =>
     {
         try
         {
             Data.Letter[] LettersControl = null;
             DateType _dType = DateType.All;
             if (!CalendarAllCheckBox.Checked)
                 _dType = (DateType)ComboBoxDate.SelectedIndex + 1;
             LettersControl = DBase.DataBase.GetLetters(TXTNumber.GetValue(), ComboProviders.Text, ComboTypes.Text, TXTFrom.Text, TXTTo.Text, TXTMoney.Text, TXTMoney2.Text, ComboUser.SelectedItem.ToString(), TextInc.Text, _dType, DateFrom.Value, DateTo.Value, loc);
             args.Result = LettersControl;
         }
         catch { args.Result = null; }
     };
     worker.RunWorkerCompleted += (s, args) =>
     {
         if (args.Result == null) return;
         AddLetters(args.Result as Data.Letter[]);
         (this.ParentForm as Form1).WaitDisable();
     };
     (this.ParentForm as Form1).WaitEnable();
     worker.RunWorkerAsync();
 }
예제 #36
0
 // Set up the BackgroundWorker object by
 // attaching event handlers.
 private void InitializeBackgoundWorker()
 {
     backgroundWorker1                     = new BackgroundWorker();
     backgroundWorker1.DoWork             += new DoWorkEventHandler(backgroundWorker1_DoWork);
     backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
     // backgroundWorker1.ProgressChanged +=                new ProgressChangedEventHandler(            backgroundWorker1_ProgressChanged);
 }
        public AtmosphereControl( )
        {
            InitializeComponent( );

            //	Populate texture resolution combo boxes
            for ( int i = 4; i <= 1024; i *= 2 )
            {
                resolutionComboBox.Items.Add( i );
            }
            resolutionComboBox.SelectedItem = m_AtmosphereBuildParameters.HeightSamples;

            m_AtmosphereBuilder = new AtmosphereBuilder( );

            mH0UpDown.Value = ( decimal )m_AtmosphereModel.MieDensityScaleHeightFraction;
            rH0UpDown.Value = ( decimal )m_AtmosphereModel.RayleighDensityScaleHeightFraction;
            //	TODO: AP: Remove bodges
            inscatterDistanceFudgeUpDown.Value = ( decimal )m_AtmosphereModel.InscatterDistanceFudgeFactor;
            outscatterDistanceFudgeUpDown.Value = ( decimal )m_AtmosphereModel.OutscatterDistanceFudgeFactor;
            outscatterFudgeUpDown.Value = ( decimal )m_AtmosphereModel.OutscatterFudgeFactor;
            mieFudgeUpDown.Value = ( decimal )m_AtmosphereModel.MieFudgeFactor;
            rayleighFudgeUpDown.Value = ( decimal )m_AtmosphereModel.RayleighFudgeFactor;

            m_Worker = new BackgroundWorker( );
            m_Worker.WorkerReportsProgress = true;
            m_Worker.WorkerSupportsCancellation = true;
            m_Worker.DoWork += BuildWorkItem;
            m_Worker.RunWorkerCompleted += WorkItemComplete;
            m_Worker.ProgressChanged += BuildProgressChanged;
        }
예제 #38
0
 internal void SpashScreen_Shown(object sender, RoutedEventArgs e)
 {
     BackgroundWorker loadapp = new BackgroundWorker();
     loadapp.DoWork += new DoWorkEventHandler(load_splash);
     loadapp.RunWorkerCompleted += new RunWorkerCompletedEventHandler(load_done);
     loadapp.RunWorkerAsync();
 }
예제 #39
0
        public FileNodes(Config config, Screensaver screensaver)
        {
            this.config       = config;
            this.screensaver  = screensaver;
            this.fileDatabase = new FileDatabase(this.screensaver.readOnly);
            //this.fileDatabase.MetadataReadEvent += new MetadataReadEventHandler(metadataShow);

            if (screensaver.action != Screensaver.Actions.Wallpaper)
            {
                this.resetFoldersQueue();

                this.backgroundWorker = new System.ComponentModel.BackgroundWorker();
                this.backgroundWorker.WorkerReportsProgress      = true;
                this.backgroundWorker.WorkerSupportsCancellation = true;
                this.backgroundWorker.DoWork             += new DoWorkEventHandler(DoWorkImageFolder);
                this.backgroundWorker.ProgressChanged    += new ProgressChangedEventHandler(progressChanged);
                this.backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(runWorkerCompleted);

                // Use local folders as this.folders is used in backgroundWorker
                //var folders = Utils.stringToConcurrentQueue(Convert.ToString(this.config.getPersistant("folders")));
                // Purge database in main thread rather, to avoid having to run database filter twice
                this.purgeNotMatchingParentFolders(this.folders);

                this.backgroundWorker.RunWorkerAsync();
            }
        }
예제 #40
0
        //自定义函数 insertData()
        private void insertData(System.ComponentModel.BackgroundWorker worker, FileInfo[] files)
        {
            SQLiteHelper.DropTable("IRunnerTable");
            SQLiteHelper.CreateTable();
            string sql = "INSERT INTO IRunnerTable(Name,Py,FilePath) values('{0}','{1}','{2}')";

            System.Collections.ArrayList al = new System.Collections.ArrayList();
            string fileName = string.Empty;
            int    i        = 0;

            foreach (FileInfo fi in files)
            {
                if (fi.Extension.Length > 0 && alFilters.Contains(fi.Extension.ToLower()))
                {
                    //SaveItemToXML(fi);
                    fileName = ConvertHelper.GetSafeSqlString(fi.Name.Split('.')[0], true);
                    al.Add(string.Format(sql, fileName, ConvertHelper.ToChineseFirstSpell(fileName), ConvertHelper.GetSafeSqlString(fi.FullName, true)));
                }

                //3.调用worker的ReportProgress函数,用来引发事件ProgressChanged
                worker.ReportProgress(i++, worker);
            }

            alFilters = null;

            SQLiteHelper.ExecuteSqlTran(al);
        }
예제 #41
0
        public Form1()
        {
            InitializeComponent();

            // Set up initial button states
            startButton.Enabled = true;
            stopButton.Enabled  = false;
            startButton.Enabled = false;

            // Set up image viewer
            VisionImage image = new VisionImage();

            imageViewer.Attach(image);

            // Enumerate cameras and update controls
            ImaqdxCameraInformation[] cameras = ImaqdxSystem.GetCameraInformation(true);
            foreach (ImaqdxCameraInformation camera in cameras)
            {
                cameraName.Items.Add(camera.Name);
            }
            cameraName.SelectedIndex = cameraName.Items.Count > 0 ? 0 : -1;

            // Set up background acquisition worker
            acquisitionWorker                            = new System.ComponentModel.BackgroundWorker();
            acquisitionWorker.DoWork                    += new DoWorkEventHandler(acquisitionWorker_DoWork);
            acquisitionWorker.RunWorkerCompleted        += new RunWorkerCompletedEventHandler(acquisitionWorker_RunWorkerCompleted);
            acquisitionWorker.ProgressChanged           += new ProgressChangedEventHandler(acquisitionWorker_ProgressChanged);
            acquisitionWorker.WorkerReportsProgress      = true;
            acquisitionWorker.WorkerSupportsCancellation = true;
        }
        public frmDoubleCarbinet(int _listening_port)
        {
            InitializeComponent();

            this.listening_port = _listening_port;

            this.pictureBox1.Paint += new PaintEventHandler(pictureBox1_Paint);
            this.MouseDown         += new MouseEventHandler(Form1_MouseDown);
            _timer          = new Timer();
            _timer.Interval = 2000;
            _timer.Tick    += new EventHandler(_timer_Tick);

            this.cmbProductName.Items.Clear();
            this.cmbProductName.Items.Add("无");
            this.cmbProductName.SelectedIndex = 0;


            this.FormClosing += new FormClosingEventHandler(SGSserverForm_FormClosing);
            this.Shown       += new EventHandler(Form1_Shown);


            //this.lblLocation.Text = string.Format("hp = {0} wp = {1}", staticClass.heightPara, staticClass.widthPara);
            this.lblStatus.Text = "";

            backgroundWorker1         = new System.ComponentModel.BackgroundWorker();
            backgroundWorker1.DoWork +=
                new DoWorkEventHandler(backgroundWorker1_DoWork);
        }
예제 #43
0
        /// <summary>
        /// 파일이동
        /// </summary>
        /// <param name="directory"></param>
        private void moveFiles(DirectoryInfo directory, System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e, CurrentState state)
        {
            try
            {
                FileInfo[]      files = directory.GetFiles();
                DirectoryInfo[] dirs  = directory.GetDirectories();

                foreach (FileInfo file in files)
                {
                    state.fileSize += file.Length;
                    //// 원본 파일의 드라이명을 USB 드라이버로 변경한다.
                    string copyto = file.FullName.Replace(this.parentFolder, this.targetDrive.RootDirectory.Name);
                    file.CopyTo(copyto);

                    state.count++;
                    state.retMessage = string.Format("{0} {1} byte copied.\r\n", file.Name, state.fileSize.ToString());
                    worker.ReportProgress(20, state);
                }

                foreach (DirectoryInfo dri in dirs)
                {
                    moveFiles(dri, worker, e, state);
                }
            }
            catch { }
        }
예제 #44
0
        private Double CalcPrime(double number, System.ComponentModel.BackgroundWorker worker, DoWorkEventArgs e)
        {
            double i, j;
            double limit = Convert.ToInt32(txtNumber.Text);

            for (i = 2; i <= limit; i++)
            {
                for (j = 2; j < i; j++)
                {
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                    }
                    else
                    {
                        if ((i % j) == 0)
                        {
                            break;
                        }
                        else if ((i % j) != 0 && j == i - 1)
                        {
                            cnt++;
                        }
                    }
                }
            }
            return(cnt + 1);
        }
예제 #45
0
        public void UpdateChangesDialog(List<KeyValuePair<GUIMod, GUIModChangeType>> changeset, BackgroundWorker installWorker)
        {
            m_Changeset = changeset;
            m_InstallWorker = installWorker;
            ChangesListView.Items.Clear();

            if (changeset == null)
            {
                return;
            }

            foreach (var change in changeset)
            {
                if (change.Value == GUIModChangeType.None)
                {
                    continue;
                }

                var item = new ListViewItem {Text = String.Format("{0} {1}", change.Key.Name, change.Key.Version)};

                var sub_change_type = new ListViewItem.ListViewSubItem {Text = change.Value.ToString()};

                item.SubItems.Add(sub_change_type);
                ChangesListView.Items.Add(item);
            }
        }
예제 #46
0
        public static void Start(int delayinms, Action action)
        {
            var bw = new System.ComponentModel.BackgroundWorker();

            bw.DoWork += (s, a) =>
            {
                System.Threading.Thread.Sleep(delayinms);

                                #if DEBUG && WINDOWS_PHONE
                try
                {
                    if (!String.IsNullOrWhiteSpace(AppStats.appForceCulture))
                    {
                        Thread.CurrentThread.CurrentCulture   = new CultureInfo(AppStats.appForceCulture);
                        Thread.CurrentThread.CurrentUICulture = new CultureInfo(AppStats.appForceCulture);
                    }
                }
                catch (Exception ex) { LittleWatson.ReportException(ex); }
                                #endif

                try
                {
                    action.Invoke();
                }
                catch (Exception ex) { LittleWatson.ReportException(ex); }
            };

            bw.RunWorkerAsync();
        }
예제 #47
0
 public ScannerProgress(string folder, BackgroundWorker worker)
 {
     this.worker = worker;
     InitializeComponent();
     UpdateFolder(folder);
     UpdateAction("");
 }
예제 #48
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            if (CheckFileNameTextBox(this.txtInputAssembly, "Please input source assembly file name at first.") == false)
            {
                return;
            }
            var w = this._Worker;

            this._Worker = null;
            if (w != null)
            {
                w.CancelAsync();
                w.Dispose();
            }
            this.txtLog.Clear();
            this._Worker                            = new BackgroundWorker();
            this._Worker.DoWork                    += _Worker_DoWork;
            this._Worker.RunWorkerCompleted        += _Worker_RunWorkerCompleted;
            this._Worker.WorkerSupportsCancellation = true;
            this.Cursor = Cursors.WaitCursor;
            ApplyConfigToProject();
            MyConsole.SetInstance(new RichTextBoxConsole(this.txtLog));
            this.btnRun.Enabled        = false;
            this.btnStop.Enabled       = true;
            this.ctlProgress.Visible   = true;
            this.btnLoadConfig.Enabled = false;
            this.btnSaveConfig.Enabled = false;
            this._Worker.RunWorkerAsync();
        }
예제 #49
0
 public void _timer_Elapsed(object sender, ElapsedEventArgs e)
 {
     Classes.CustomSnapshotRoot root = null;
     Classes.KeeperAPI keeper = new Classes.KeeperAPI();
     Action workAction = delegate
     {
         BackgroundWorker worker = new BackgroundWorker();
         worker.DoWork += delegate
         {
             root = keeper.getKeeperInfo(guid);
         };
         worker.RunWorkerCompleted += delegate
         {
             try {
                 //image.Source = null;
                 Classes.ScoreboardRenderer render = new Classes.ScoreboardRenderer(this, root.snapshot.mapId, root);
             }catch(Exception ex)
             {
                 Classes.Logger.addLog(ex.ToString(), 1);
             }
             //Update code in here
         };
         worker.RunWorkerAsync();
     };
     Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, workAction);
 }
예제 #50
0
        private void ProcessFileUpload(System.Uri uri
                                       , System.IO.FileInfo fileInfo
                                       , System.ComponentModel.BackgroundWorker worker
                                       , System.ComponentModel.DoWorkEventArgs e)
        {
            using (FileStream stream = fileInfo.OpenRead())
            {
                int  i        = 0;
                bool finished = false;
                while (!finished)
                {
                    MemoryStream chunk      = new MemoryStream();
                    Chunk        chunkToAdd = new Chunk()
                    {
                        FileName = uniqueFileNameNonUI, Number = i, Size = 1
                    };
                    currentDispatcher.BeginInvoke(() =>
                    {
                        Chunks.Add(chunkToAdd);
                    });

                    //Compress to get a 3MB Chunk of file
                    finished = CreateZippedChunk(stream, chunk, 4096, 3000000, "zip" + i.ToString(), chunkToAdd);
                    //Upload Chunk
                    UploadChunk(uri, chunk, worker, e, i, finished, chunkToAdd);
                    i++;
                }
            }
        }
예제 #51
0
 private void CreateBackgroundWorker()
 {
     worker = new BackgroundWorker();
     worker.DoWork += new DoWorkEventHandler(worker_DoWork);
     worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
     worker.WorkerSupportsCancellation = true;
 }
예제 #52
0
 private static void UpdateCheck()
 {
     Game.PrintChat("<font color='#33FFFF'>>>LeagueSharp.Common loaded <<");
     var bgw = new BackgroundWorker();
     bgw.DoWork += bgw_DoWork;
     bgw.RunWorkerAsync();
 }
예제 #53
0
        public override void Start(SUAppcastItem item, string path) {

            BackgroundWorker unzipper = new BackgroundWorker();
            unzipper.DoWork += UnzipFile;
            unzipper.RunWorkerCompleted += UnzipCompleted;
            unzipper.RunWorkerAsync(path);
        }
예제 #54
0
        /// <summary>
        /// Lance une tache dans un background worker.
        /// </summary>
        /// <param name="taskFunc">Tache à exécuter.</param>
        /// <param name="completionAction">Action à réaliser après l'exécution. Recoit l'exception si une exception a eu lieu.</param>
        public static void Start(Action taskFunc, Action<Exception> completionAction)
        {
            if (taskFunc == null)
            {
                throw new ArgumentNullException("taskFunc");
            }

            var backgroundWorker = new BackgroundWorker();

            backgroundWorker.DoWork += new DoWorkEventHandler(
                delegate
                {
                    taskFunc();
                });

            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
                delegate(object sender, RunWorkerCompletedEventArgs e)
                {
                    if (completionAction != null)
                    {
                        completionAction(e.Error);
                    }
                });

            backgroundWorker.RunWorkerAsync();
        }
예제 #55
0
        /* Download File */


        public void download(string remoteFile, string localFile, System.ComponentModel.BackgroundWorker backgroundWorker1)
        {
            try
            {
                long test = this.getFileSize(remoteFile);
                /* Create an FTP Request */
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
                /* Log in to the FTP Server with the User Name and Password Provided */
                ftpRequest.Credentials = new NetworkCredential(user, pass);
                /* When in doubt, use these options */
                ftpRequest.UseBinary  = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive  = true;
                /* Specify the Type of FTP Request */
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

                /* Establish Return Communication with the FTP Server */
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                /* Get the FTP Server's Response Stream */
                ftpStream = ftpResponse.GetResponseStream();

                /* Open a File Stream to Write the Downloaded File */
                FileStream localFileStream = new FileStream(localFile, FileMode.Create);
                /* Buffer for the Downloaded Data */
                byte[] byteBuffer = new byte[bufferSize];
                int    bytesRead  = ftpStream.Read(byteBuffer, 0, bufferSize);
                /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
                long sizeMax = test;


                try
                {
                    int totalReadBytesCount = 0;

                    while (bytesRead > 0)
                    {
                        localFileStream.Write(byteBuffer, 0, bytesRead);
                        bytesRead            = ftpStream.Read(byteBuffer, 0, bufferSize);
                        totalReadBytesCount += bytesRead;
                        var progress = totalReadBytesCount * 100.0 / sizeMax;
                        if (backgroundWorker1 != null)
                        {
                            backgroundWorker1.ReportProgress((int)progress);
                        }
                    }

                    var progresss = 100;

                    // backgroundWorker1.ReportProgress((int)progresss);
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                /* Resource Cleanup */
                localFileStream.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            return;
        }
        public TemperatureSequenceEditor(ENUM_Window_Mode Mode)
        {
            InitializeComponent();

            _vm = new ViewModel_TemperatureSequenceEditor();

            /* 加载Sequence Names */
            bgw_Init = new BackgroundWorker();
            bgw_Init.WorkerReportsProgress = true;
            bgw_Init.DoWork += bgw_Init_DoWork;
            bgw_Init.ProgressChanged += bgw_Init_ProgressChanged;
            bgw_Init.RunWorkerAsync();

            /* 根据模式设置界面 */
            if (Mode == ENUM_Window_Mode.Load)
            {
                btn_New.Visibility = Visibility.Hidden;
                btn_Save.Visibility = System.Windows.Visibility.Hidden;
                btn_Delete.Visibility = System.Windows.Visibility.Hidden;
                btn_Load.Visibility = System.Windows.Visibility.Visible;
                grid_SequenceEdit.IsEnabled = false;
            }
            else
            {
                btn_New.Visibility = Visibility.Visible;
                btn_Save.Visibility = System.Windows.Visibility.Visible;
                btn_Delete.Visibility = System.Windows.Visibility.Visible;
                btn_Load.Visibility = System.Windows.Visibility.Hidden;
                grid_SequenceEdit.IsEnabled = true;
            }
        }
예제 #57
0
파일: Form1.cs 프로젝트: persinac/JobFinder
        public Form1()
        {
            InitializeComponent();
            util = new Utility();
            mainJobList = new BindingList<IndeedDetails>();
            filtered = new List<IndeedDetails>();
            sortKeeper = new GridSortBy();
            //worker stuff
            worker = new BackgroundWorker();

            worker.DoWork += BackgroundWorkerDoWork;
            worker.RunWorkerCompleted +=
               BackgroundWorkerRunWorkerCompleted;

            string file_name = @"C:\Users\apersinger\Documents\Misc\jsonjobs.txt";
            string file_contents = util.OpenFile(file_name);
            if(file_contents.Length > 0) {
                data = util.DeserializeString(file_contents);
                mainJobList = new BindingList<IndeedDetails>(data);
                dataGridView1.DataSource = mainJobList;
            }

            txtURL.Text = "www.indeed.com";
            txtLocation.Text = "california";
            txtJobTitle.Text = "software";

            btnFilterResults.Enabled = false;
        }
예제 #58
0
 public void Run()
 {
     BackgroundWorker transferTablesWorker = new BackgroundWorker();
     transferTablesWorker.DoWork += new DoWorkEventHandler(TransferTablesWorker_DoWork);
     transferTablesWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(TransferTablesWorker_RunWorkerCompleted);
     transferTablesWorker.RunWorkerAsync();
 }
예제 #59
0
 //bool toCancelReceive = false;
 /// <summary>
 /// Асинхронно и рекурсивно добавляет набор файлов и директорий в кассету в указанную коллекцию
 /// и возвращает набор добавленных в базу данных XElement-записей - это для синхронизации
 /// </summary>
 /// <param name="filenamesAndCollectionId">К массиву имен файлов и директорий, последним элементом прикреплен (добавлен) идентификатор коллекции, в которую записываются внешние файлы</param>
 /// <param name="worker"></param>
 /// <param name="e"></param>
 /// <returns></returns>
 private IEnumerable<XElement> AddFilesAndDirectoriesAsync(string[] filenamesAndCollectionId,
     BackgroundWorker worker, DoWorkEventArgs e)
 {
     List<XElement> addedElements = new List<XElement>();
     string[] filenames = filenamesAndCollectionId.Take(filenamesAndCollectionId.Length - 1).ToArray();
     string collectionId = filenamesAndCollectionId[filenamesAndCollectionId.Length - 1];
     // правильно посчитаю число вводимых файлов
     int fnumber = 0;
     foreach (string fn in filenames)
     {
         if (File.Exists(fn)) { if (fn != "Thumbs.db") fnumber++; }
         else fnumber += 1 + CountTotalFiles(new DirectoryInfo(fn));
     }
     // а теперь добавлю файлы и директории с
     int count = 0;
     foreach (string fname in filenames)
     {
         if (worker.CancellationPending) break;
         if (File.Exists(fname))
         {
             if (fname != "Thumbs.db")
                 addedElements.AddRange(this.cass.AddFile(new FileInfo(fname), collectionId));
             count++;
             worker.ReportProgress(100 * count / fnumber);
         }
         else if (Directory.Exists(fname))
         {
             //smallImageFullNames.AddRange(this.cass.AddDirectory(new DirectoryInfo(fname), collectionId));
             addedElements.AddRange(AddDirectoryAsync(new DirectoryInfo(fname), collectionId, ref count, fnumber, worker));
         }
     }
     return addedElements;
 }
예제 #60
-1
        // Constructor
        public MainPage( )
        {
            InitializeComponent();

            myPopup = new Popup() { IsOpen = true, Child = new SplashScreen() };
            backroungWorker = new BackgroundWorker();
            RunBackgroundWorker();

            using(AppDbContext context = new AppDbContext("Data Source='isostore:/AccountAssistantDb.sdf'"))
            {
                if(!context.DatabaseExists())
                {
                    context.CreateDatabase();

                }
            }
            if(!IsolatedStorageSettings.ApplicationSettings.Contains("situation"))
                IsolatedStorageSettings.ApplicationSettings.Add("situation", true);

            if(!IsolatedStorageSettings.ApplicationSettings.Contains("TilePerson"))
                IsolatedStorageSettings.ApplicationSettings.Add("TilePerson", "");

            if(!IsolatedStorageSettings.ApplicationSettings.Contains("TileSituation"))
                IsolatedStorageSettings.ApplicationSettings.Add("TileSituation", "");
        }