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; }
internal CRTBaseMath( BackgroundWorker UseWorker, CRTMath UseCRTMath ) { // Most of these are created ahead of time so that // they don't have to be created inside a loop. Worker = UseWorker; IntMath = new IntegerMath(); CRTMath1 = UseCRTMath; Quotient = new Integer(); Remainder = new Integer(); CRTAccumulateBase = new ChineseRemainder( IntMath ); CRTAccumulateBasePart = new ChineseRemainder( IntMath ); CRTAccumulateForBaseMultiples = new ChineseRemainder( IntMath ); CRTAccumulatePart = new ChineseRemainder( IntMath ); BaseModArrayModulus = new Integer(); CRTTempForIsEqual = new ChineseRemainder( IntMath ); CRTWorkingTemp = new ChineseRemainder( IntMath ); ExponentCopy = new Integer(); CRTXForModPower = new ChineseRemainder( IntMath ); CRTAccumulate = new ChineseRemainder( IntMath ); CRTCopyForSquare = new ChineseRemainder( IntMath ); FermatExponent = new Integer(); CRTFermatModulus = new ChineseRemainder( IntMath ); FermatModulus = new Integer(); CRTTestFermat = new ChineseRemainder( IntMath ); Worker.ReportProgress( 0, "Setting up numbers array." ); SetupNumbersArray(); Worker.ReportProgress( 0, "Setting up base array." ); SetupBaseArray(); Worker.ReportProgress( 0, "Setting up multiplicative inverses." ); SetMultiplicativeInverses(); }
public void TakeFullSnapshot( FileGroup[] fileGroups, string[] languageCodes, // Source _and_ destination. BackgroundWorker bw) { languageCodes = make2(languageCodes); bw.ReportProgress(0, Resources.SnapshotController_TakeFullSnapshot_Taking_snapshots_); var fgIndex = 0; foreach (var fileGroup in fileGroups) { bw.ReportProgress( 0, string.Format( Resources.SnapshotController_TakeFullSnapshot_Taking_snapshot__0__of__1__for_file_group___2_____, fgIndex + 1, fileGroups.Length, fileGroup.GetNameIntelligent(Project))); if (bw.CancellationPending) { throw new OperationCanceledException(); } doTakeSnapshot(fileGroup, languageCodes, bw); fgIndex++; } }
public WorkerControl() { InitializeComponent(); m_worker = new BackgroundWorker(); // Wire Events for BackGround Worker m_worker.DoWork += (s, e) => { for(int i = 0; i < 100; i++) { Thread.Sleep(m_second); m_worker.ReportProgress(i); if(m_worker.CancellationPending) { e.Cancel = true; m_worker.ReportProgress(0); return; } } }; m_worker.ProgressChanged += (s, e) => { pb_progress.Value = e.ProgressPercentage; }; m_worker.RunWorkerCompleted += (s, e) => { if(e.Cancelled) { // Report the task was Canceled } }; m_worker.WorkerReportsProgress = true; m_worker.WorkerSupportsCancellation = true; }
public void AutoAllocate(BackgroundWorker worker) { // just fills whatever we have :) int loopCount = 0; worker.ReportProgress(0, "Seeding..."); foreach (Enrollment e in EnrollList) { if (e.Enrolled || e.GetRestricted() != null) continue; Trace.WriteLine("Enroll " + e); e.Enrolled = true; worker.ReportProgress(10 * (++loopCount) / EnrollList.Count); } FullFillExcel(); // do some magic, A* search! worker.ReportProgress(10, "Optimizing..."); visited = new HashSet<string>(); queue = new List<State>(QUEUE_LIMIT); best = null; Trace.WriteLine("Start time: " + DateTime.Now.ToLongTimeString()); #if DEBUG long lastTime = DateTime.Now.Ticks; #endif CheckVisit(EnrollStatus); Queue(EnrollStatus); for (int i = 0; i < PROCESS_ROUND; i++) { State s = queue[0]; queue.RemoveAt(0); Process(s); SortAndDrop(); _objGen++; Trace.WriteLine("> i=" + i + ", B: " + best + ", H: " + queue[0] + ", W: " + queue[queue.Count - 1]); #if DEBUG long now = DateTime.Now.Ticks; Debug.Print("Time: " + (now - lastTime)); lastTime = now; #endif worker.ReportProgress(10 + 90 * i / PROCESS_ROUND); Thread.Yield(); } Trace.WriteLine("End time: " + DateTime.Now.ToLongTimeString()); CacheClean(); visited = null; queue = null; System.GC.Collect(); System.GC.WaitForPendingFinalizers(); // Final Output worker.ReportProgress(100, "Finishing..."); EnrollStatus = best; FullFillExcel(); best = null; }
// Run this as a BackgroundWorker method. Will report 0 whenever it starts saving and 1 whenever it is // done saving through the ProgressChanged event. public void SavePeriodically(BackgroundWorker worker) { IsRunning = true; LastSave = DateTime.Now; worker.WorkerReportsProgress = true; try { while ( !ShutdownRequest ) { var t = (DateTime.Now - LastSave).TotalMilliseconds; if ( (SaveRequest || t >= Interval) && UnsavedChanges ) { bool props, lessees, projects; lock ( UnsavedChangesChanging ) { SaveRequest = false; // This section allows changes to be registered props = PropertiesChanged; // while the writing commences. While they may be picked lessees = LesseesChanged; // up on the current write, this makes sure there is another projects = ProjectsChanged; // write coming up in case they aren't PropertiesChanged = LesseesChanged = ProjectsChanged = false; } worker.ReportProgress(0); if ( props ) Xml.Write(PropertyManagerReference, PropertyFilepath, IdTable); if ( lessees ) Xml.Write(LesseeManagerReference, LesseeFilepath, IdTable); if ( projects ) Xml.Write(ProjectManagerReference, ProjectPath, IdTable); LastSave = DateTime.Now; worker.ReportProgress(1); } Thread.Sleep(Timestep); } } finally { IsRunning = false; } }
public static void InstallApplication(BackgroundWorker bgw) { bgw.ReportProgress(5); if (Startup) SetStartupRegistry(); bgw.ReportProgress(10); //string InstallLocation = @"C:\Program Files (x86)\Remotocon"; string pluginsFolder = Path.Combine(InstallDirectory, "Plugins"); if (!Directory.Exists(InstallDirectory)) Directory.CreateDirectory(InstallDirectory); if (!Directory.Exists(pluginsFolder)) Directory.CreateDirectory(pluginsFolder); string remotoconFilePath = Path.Combine(InstallDirectory, "remotocon.exe"); string remotoconConfigPath = Path.Combine(InstallDirectory, "remotocon.exe.config"); File.WriteAllBytes(remotoconFilePath, Files.remotocon_exe); bgw.ReportProgress(60); string EncryptedPass = GetEncryptedPass(); bgw.ReportProgress(80); WriteConfigFile(EncryptedPass, UserName, Port, Dedicated); bgw.ReportProgress(100); }
protected override void doSpecificWork(BackgroundWorker worker, DoWorkEventArgs args) { String msg; Boolean result = false; try { worker.ReportProgress(0, Constantes.getMessage("ReportProgress_BD")); result = this.chargeData.clearAllDataBase(worker); } catch (Exception ex) { msg = "Error: Problemas Borrando los datos almacenados."; this.modLog.Error(msg + ex.Message); } finally { if (result) { worker.ReportProgress(100, Constantes.getMessage("ReportProgress_B")); } else { throw new Exception("WorkerErrorDeletingData"); } } }
/// <summary> /// Import dat z XML 'ds_dphz.xml' /// </summary> /// <param name="path"></param> public static int ImportDataFromXml(string path, string dbName, BackgroundWorker bw) { var entities = new List<BlackListEntity>(); bw.ReportProgress(0, "Čítanie vstupného súboru.."); // nacitanie entit z xml LoadEntitiesFromXml(path, entities); // zmazanie starych zaznamov var db = DbProvider.CreateProvider(dbName); new BlackListEntity(db);//init tabuliek db.ExecuteNonQuery(string.Format("delete from {0}", BlackListEntity.TABLE_NAME)); // ulozenie novych using (var con = db.GetConnection()) { con.Open(); using (var tr = con.BeginTransaction()) { for (int i = 0; i < entities.Count; i++) { entities[i].Save(con, tr); bw.ReportProgress((int)((double)(i + 1) / entities.Count * 100), "Aktualizácia databázy DIČ (black-list).."); } tr.Commit(); } con.Close(); } return entities.Count; }
protected override void doSpecificWork(BackgroundWorker worker, DoWorkEventArgs args) { String msg; Boolean result = false; try { worker.ReportProgress(10, Constantes.getMessage("MsgMailSendingStatus")); Report.sendMail(emailAddress, excel, pdf); result = true; } catch (Exception ex) { msg = "Error: Problemas enviando los informes por correo electrónico"; this.modLog.Error(msg + ex.Message); } finally { if (result) { worker.ReportProgress(100, Constantes.getMessage("InfoMsgMailSent")); } else { throw new Exception("ErrorMsgMailSent"); } } }
// function for adding new layers private void addButton_Click(object sender, EventArgs e) { // file dialog for selecting one or more files OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "shp files|*.shp"; openFileDialog1.Multiselect = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { // initialises values for the progress bar progressBar.Minimum = 0; progressBar.Maximum = openFileDialog1.FileNames.Count(); progressBar.Value = 0; // background worker for reading new layers in another thread BackgroundWorker bw = new BackgroundWorker(); bw.WorkerReportsProgress = true; // list of new layers List<Layer> readLayers = new List<Layer>(); bw.DoWork += (object wsender, DoWorkEventArgs we) => { // read each layer in turn foreach (String file in openFileDialog1.FileNames) { bw.ReportProgress(0, file.Split('\\').Last()); Layer l = ShpReader.read(file); bw.ReportProgress(1); readLayers.Insert(0, l); } }; bw.RunWorkerCompleted += (object wsender, RunWorkerCompletedEventArgs we) => { // reset progress bar progressBar.Value = 0; progressLabel.Text = ""; // add each layer and focus screen on the new layer foreach (Layer l in readLayers) { Layers.Insert(0, l); ScreenManager.RealRect.Set(l.Boundingbox); } if (layerList.Items.Count > 0) layerList.SelectedIndex = 0; ScreenManager.Calculate(); redraw(); }; bw.ProgressChanged += (object wsender, ProgressChangedEventArgs we) => { // update progress barvel, progressBar.Value += we.ProgressPercentage; if (we.ProgressPercentage == 0) progressLabel.Text = "Reading " + (string)we.UserState; }; bw.RunWorkerAsync(); } }
public void descargaOpen(String jobid, BackgroundWorker bgw) { EmailInfo einf = new EmailInfo(); Send objSend = einf.getEmailInformationOpenSent(jobid); double deci = Convert.ToDouble(objSend.UniqueOpens); Conexion conex =new Conexion(); RetrieveRequest rr = new RetrieveRequest(); rr.ObjectType = "OpenEvent"; String[] props = { "SubscriberKey" }; rr.Properties = props; /** * Details for single JobId/SendId */ SimpleFilterPart filter = new SimpleFilterPart(); filter.Property = "SendID"; String[] vlaues = { jobid + " " }; filter.Value = vlaues; rr.Filter = filter; APIObject[] results = null; String requestId = null; String status; List<String> lista = new List<String>(); int k = 0; int porcentaje; do { status = conex.cliente.Retrieve(rr, out requestId, out results); for (int i = 0; i < results.Length; i++) { OpenEvent deo = results[i] as OpenEvent; string parte3 = deo.SubscriberKey; var newLine = string.Format("{0}", parte3); lista.Add(newLine); porcentaje = Convert.ToInt32((k / deci) * 100); if (porcentaje > 100) porcentaje = 100; bgw.ReportProgress(porcentaje); k++; } rr = new RetrieveRequest(); rr.ContinueRequest = requestId; System.Console.Out.WriteLine("Procesando...."); System.Console.Out.WriteLine(results.Length); } while (status.Equals("MoreDataAvailable")); List<String> sinDup = lista.Distinct().ToList(); System.Console.Out.WriteLine("Descarga Completa!"); StreamWriter file = new StreamWriter(@"D:\ET_EXTRACTOR\Open_" + jobid + ".txt", true); System.Console.Out.WriteLine("Formateando"); for (int j = 0; j < sinDup.Count; j++) { file.WriteLine(sinDup.ElementAt(j)); } file.Close(); bgw.ReportProgress(0); }
public void Close(BackgroundWorker worker) { using (var ts = new TransactionScope()) { var context = new ERPContext(); var accounts = context.Ledger_Accounts .Include("LedgerGeneral") .Include("LedgerAccountBalances") .ToList(); var revenueAndExpenseAccounts = context.Ledger_Accounts .Include("LedgerGeneral") .Include("LedgerAccountBalances") .Where(e => e.Class.Equals("Expense") || e.Class.Equals("Revenue")) .ToList(); var index = 1; var totalAccounts = accounts.Count + revenueAndExpenseAccounts.Count; // Close the Revenue and Expense Accounts to Retained Earnings foreach (var account in revenueAndExpenseAccounts) { if (account.LedgerGeneral.Debit != 0 || account.LedgerGeneral.Credit != 0) CloseRevenueOrExpenseAccountToRetainedEarnings(account, context); worker.ReportProgress(index++ * (totalAccounts / 100)); } foreach (var account in accounts) { if (UtilityMethods.GetCurrentDate().Month == 12) { var newBalance = new LedgerAccountBalance { LedgerAccount = account, PeriodYear = UtilityMethods.GetCurrentDate().Year + 1 }; context.Ledger_Account_Balances.Add(newBalance); } if (Period != 12) account.LedgerGeneral.Period++; else { account.LedgerGeneral.PeriodYear++; account.LedgerGeneral.Period = 1; } // Close the balances if (account.Class.Equals("Asset") || account.Class.Equals("Expense")) CloseAssetOrExpenseAccount(account, context); else CloseLiabilityOrRevenueAccount(account, context); worker.ReportProgress(index++ * (totalAccounts / 100)); } context.SaveChanges(); ts.Complete(); } OnPropertyChanged("PeriodYear"); OnPropertyChanged("Period"); }
public void CopyFile(object sender, DoWorkEventArgs e) { _bw = (BackgroundWorker) sender; string status = Processing.GetResourceString("fileworker_copy_file"); _bw.ReportProgress(-10, status); _bw.ReportProgress(0); DoCopyFile(); }
/* * public static FullSpriteSet FromPsxISO( string filename, BackgroundWorker worker ) * { * using ( FileStream stream = File.OpenRead( filename ) ) * { * return FromPsxISO( stream, worker ); * } * } * * public static FullSpriteSet FromPsxISO( Stream stream, BackgroundWorker worker ) * { * return DoInitPSX( stream, worker ); * } * * public static FullSpriteSet FromPspISO( string filename, BackgroundWorker worker ) * { * using ( FileStream stream = File.OpenRead( filename ) ) * { * return FromPspISO( stream, worker ); * } * } * * public static FullSpriteSet FromPspISO( Stream stream, BackgroundWorker worker ) * { * return DoInitPSP( stream, worker ); * } */ public static FullSpriteSet FromShishiFile(string filename, System.ComponentModel.BackgroundWorker worker) { Dictionary <string, Dictionary <string, List <string> > > manifest; List <AbstractSprite> sprites = new List <AbstractSprite>(); int tasks = 0; int tasksComplete = 0; using (ZipFile zf = new ZipFile(filename)) { BinaryFormatter f = new BinaryFormatter(); manifest = f.Deserialize(zf.GetInputStream(zf.GetEntry("manifest"))) as Dictionary <string, Dictionary <string, List <string> > >; foreach (KeyValuePair <string, Dictionary <string, List <string> > > kvp in manifest) { tasks += kvp.Value.Keys.Count * 3; } tasks += 1; foreach (string type in manifest.Keys) { Type spriteType = Type.GetType(type); ConstructorInfo constructor = spriteType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(SerializedSprite) }, null); foreach (string name in manifest[type].Keys) { List <string> filenames = manifest[type][name]; int size = filenames.Count; byte[][] bytes = new byte[size][]; worker.ReportProgress((tasksComplete++ *100) / tasks, string.Format("Extracting {0}", name)); ZipEntry entry = zf.GetEntry(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}/Pixels", type, name)); byte[] pixels = new byte[entry.Size]; StreamUtils.ReadFully(zf.GetInputStream(entry), pixels); entry = zf.GetEntry(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}/Palettes", type, name)); byte[] palettes = new byte[entry.Size]; StreamUtils.ReadFully(zf.GetInputStream(entry), palettes); entry = zf.GetEntry(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}/Size", type, name)); byte[] sizeBytes = new byte[entry.Size]; StreamUtils.ReadFully(zf.GetInputStream(entry), sizeBytes); int origSize = Int32.Parse(new string( Encoding.UTF8.GetChars(sizeBytes)), System.Globalization.CultureInfo.InvariantCulture); worker.ReportProgress((tasksComplete++ *100) / tasks, string.Format("Building {0}", name)); sprites.Add(constructor.Invoke(new object[] { new SerializedSprite(name, origSize, filenames, pixels, palettes) }) as AbstractSprite); } } } return(new FullSpriteSet(sprites, worker, tasksComplete, tasks)); }
public void Run(BackgroundWorker backgroundWorker, string path, string server, int controlPort, int dataPort, int xmitConnectionCount, int xmitFragmentBytes) { mBackgroundWorker = backgroundWorker; GC.Collect(); try { using (var client = new TcpClient(server, controlPort)) { using (var stream = client.GetStream()) { using (var bw = new BinaryWriter(stream)) { mBackgroundWorker.ReportProgress(1, "Connected to Server.\n"); // XmitTaskのリストを準備。 mBackgroundWorker.ReportProgress(1, string.Format("Reading {0} onto memory... ", path)); Stopwatch sw = new Stopwatch(); sw.Start(); var totalBytes = mClientXmitter.SetupXmitTasks(path, xmitFragmentBytes); sw.Stop(); mBackgroundWorker.ReportProgress(1, string.Format("{0} seconds\n", sw.ElapsedMilliseconds / 1000.0)); mBackgroundWorker.ReportProgress(1, "Calculating MD5 hash... "); sw.Reset(); sw.Start(); mClientXmitter.CalcHash(); sw.Stop(); mBackgroundWorker.ReportProgress(1, string.Format("{0} seconds\n", sw.ElapsedMilliseconds / 1000.0)); // 設定情報を送出。 if (!SendSettings(stream, bw, xmitConnectionCount, xmitFragmentBytes, totalBytes)) { mBackgroundWorker.ReportProgress(100, "Error: Unexpected server response. Exit."); return; } // 2. 送出データを準備し、Xmit用TCP接続をxmitConnectionCount個確立する。 // Xmit用TCP接続を確立 mClientXmitter.EstablishConnections(server, dataPort, xmitConnectionCount); mBackgroundWorker.ReportProgress(1, string.Format("Data connection established. sending {0}MB stream...\n", totalBytes / ONE_MEGA)); // 3. xmitConnectionCount個のTCP接続を使用して送出。 Xmit(stream, bw); mClientXmitter.CloseConnections(); } } } } catch (ArgumentNullException e) { mBackgroundWorker.ReportProgress(0, string.Format("Error: ArgumentNullException: {0}\n", e)); } catch (SocketException e) { mBackgroundWorker.ReportProgress(0, string.Format("Error: SocketException: {0}\n", e)); } mBackgroundWorker.ReportProgress(100, "Done.\n"); }
public void Proceed(BackgroundWorker worker) { worker.ReportProgress(0, "Обработка файла"); var items = ParseFile(); var b = CollectBorrowers(items); var e = CollectExisting(); worker.ReportProgress(1, "Создание структуры папок"); CreateFolderTree(b); worker.ReportProgress(2, "Перемещение завершенных заявок"); MoveCompleted(b, e); }
private void glitchEffect_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { Random r = new Random(); for (int i = 0; i < 3; i++) { glitchEffect.ReportProgress(1, r.NextDouble()); System.Threading.Thread.Sleep(r.Next(25, 250)); glitchEffect.ReportProgress(1, 1); System.Threading.Thread.Sleep(r.Next(25, 250)); } }
/// <summary> /// Main generating method which prepares all the data and generates the graph. /// </summary> /// <param name="worker">For reporting progress outside as this method runs a loong time (due to downloading)</param> public static void GenerateGraph(BackgroundWorker worker = null) { // load friendlist of our user FriendList friends = GraphAPI.GetData<FriendList>(Config.USER_ID + "/friends"); // report that loading was fine worker.ReportProgress(0, friends.Count); // make sure the report made it through and updated GUI // this is necessary because the System.Threading.Thread.Yield(); // create destination directories if(!File.Exists("cache")) { System.IO.Directory.CreateDirectory("cache"); } string dir = "cache/" + Config.USER_ID; if(!File.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } if(!File.Exists(dir + "/photos")) { System.IO.Directory.CreateDirectory(dir + "/photos"); } // load all mutual friends and the whole graph Graph graph = new Graph(); // if we had loaded the friend information earlier we dont need to redownload it if(File.Exists(dir + "/data.json")) { graph.LoadConnections(dir + "/data.json", worker); } else { graph.LoadConnections(friends, worker); graph.SaveConnections(dir + "/data.json"); } // download profile pictures of the users DownloadPictures(friends, dir + "/photos", worker); // now we generate the graph (vertices positions) // gets map of type: Person -> (x,y) graph.Calculate(worker); // and we draw it to a file Bitmap bmp = DrawGraph(graph.Data, dir, worker); bmp.Save(dir + "/graph.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); bmp.Dispose(); worker.ReportProgress(100, dir + "/graph.jpg"); }
/// <summary> /// 환자정보 파일 복사하기 /// </summary> /// <param name="worker"></param> /// <param name="e"></param> public void ExecJob(System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e) { CurrentState state = new CurrentState(); state.fileSize = 0; state.retCode = 0; state.count = 0; state.retMessage = "파일복사 시작 >>> \r\n"; worker.ReportProgress(1, state); if (worker.CancellationPending) { state.retCode = 0; state.retMessage = "파일복사가 작업자에 의해 취소되었습니다.\r\n"; worker.ReportProgress(100, state); e.Cancel = true; } else { try { if (srcDir.Exists) { this.parentFolder = string.Format("{0}\\", srcDir.FullName); //1.폴더생성 this.CreatdFolder(srcDir); //2.파일복사 this.moveFiles(srcDir, worker, e, state); state.retMessage = "Copying files done.\r\n"; worker.ReportProgress(100, state); } else { state.retCode = -1; state.retMessage = "파일복사 중 에러발생.\r\n"; worker.ReportProgress(100, state); } } catch (Exception ex) { state.retCode = -1; state.retMessage = "파일복사 중 에러발생.\r\n"; worker.ReportProgress(100, state); } e.Result = state; } }
public void parallelPingServers(System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e, int[] speeds, ARSMonitor.serverControl server ) { Ping pingSender = new Ping(); PingOptions options = new PingOptions(); options.DontFragment = true; string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // сделать размер буфера изменяемым в настройках CurrentState state = new CurrentState(); byte[] buffer = Encoding.ASCII.GetBytes(data); // сделать изменяемым в настройках int timeout = 120; // сделать изменяемым в настройках double count = serverList.Count; double i = 0; int progress; i++; progress = (int)Math.Round((i / count) * 100); //elements.Find(el => el.Child == server); string host = server.objectAddress; // сделать изменяемым в настройках while (!worker.CancellationPending) { PingReply reply = pingSender.Send(host, timeout, buffer, options); if (reply.Status == IPStatus.Success) { state.address = server.objectAddress; state.isOnline = true; /*while (worker.IsBusy) * System.Threading.Thread.Sleep(100);*/ worker.ReportProgress(progress, state); } else { state.address = server.objectAddress; state.isOnline = false; worker.ReportProgress(progress, state); } if (!workState) { System.Threading.Thread.Sleep(1000); } System.Threading.Thread.Sleep(speeds[1]); } e.Cancel = true; }
public void AddRulesFromUser(Entity sourceUser, List<Entity> users, BackgroundWorker worker = null) { // Retrieving user filter metadata var emd = (RetrieveEntityResponse) service.Execute(new RetrieveEntityRequest { EntityFilters = EntityFilters.Attributes, LogicalName = "userquery" }); if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Loading source user synchronization filters..."); } // Retrieve filters for source user var rules = GetRules(new[] { 16, 256 }, new List<Entity> { new Entity("systemuser") { Id = sourceUser.Id } }); foreach (var targetUser in users) { if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Removing filters from user " + targetUser.GetAttributeValue<string>("fullname") + "..."); } // Remove existing rules RemoveAllRulesForUser(targetUser.Id); //ApplyRulesToUser(new EntityReferenceCollection(rules.Entities.Where(e=>e.GetAttributeValue<EntityReference>("parentqueryid") != null).Select(e=>e.GetAttributeValue<EntityReference>("parentqueryid")).ToList()), targetUserId); if (worker != null && worker.WorkerReportsProgress) { worker.ReportProgress(0, "Adding filters to user " + targetUser.GetAttributeValue<string>("fullname") + "..."); } // Add source rules to target user foreach (var rule in rules.Entities) { rule.Id = Guid.Empty; rule.Attributes.Remove("userqueryid"); rule["ownerid"] = new EntityReference("systemuser", targetUser.Id); foreach (var amd in emd.EntityMetadata.Attributes.Where(a => a.IsValidForCreate.Value == false)) { rule.Attributes.Remove(amd.LogicalName); } service.Create(rule); } } }
protected override void doSpecificWork(BackgroundWorker worker, DoWorkEventArgs args) { Boolean result = false; String error = ""; try { this.modLog.Info("Borramos todos los comandos y categorias almacenados en la base de datos, antes de cargar el fichero de comandos iniciales"); worker.ReportProgress(0, Constantes.getMessage("ReportProgress_BD")); if (!this.chargeData.restartDataBase(worker)) { throw new AppProcessException("RestartDataBaseErrorDeletingPreviousData"); } worker.ReportProgress(15, Constantes.getMessage("ReportProgress_LFCI")); this.modLog.Info("Cargamos las categorías y comandos iniciales en la Base de Datos"); worker.ReportProgress(20); this.initialCharge.chargeTables(worker); this.modLog.Info("Fichero de Comandos Iniciales cargado correctamente en la Base de Datos"); result = true; } catch (AppProcessException ex) { result = false; this.modLog.Error(ex); error = ex.ExCode; } catch (Exception ex) { result = false; this.modLog.Error(ex); error = "WorkerErrorRestartDB"; } finally { if (result) { worker.ReportProgress(100, Constantes.getMessage("ReportProgress_C2")); } else { throw new Exception(error); } } }
/// <summary> /// Método para cargar el Fichero de Comandos Iniciales con sus parámetros /// Cargamos las tablas de la base de datos con los comandos y categorias que vamos a tener en cuenta /// </summary> public void chargeTables(BackgroundWorker worker) { Category cat; modLog.Info("Leemos la información contenida en el fichero de Comandos Iniciales."); if (!this.readCommandsFile(worker)) { throw new AppProcessException("InitialChargeErrorReadingExcelFile"); } modLog.Info("Fichero de Comandos Iniciales leído."); modLog.Info("Cargamos las CATEGORIAS en la tabla CATEGORIES"); worker.ReportProgress(80, Constantes.getMessage("ReportProgress_CC")); if (!this.newData.chargeCategories(this.categoriesList)) { throw new AppProcessException("InitialChargeErrorSavingCategories"); } modLog.Info("Categorias Iniciales Cargadas en la Base de Datos"); // Rellenamos la categoría de los Comandos worker.ReportProgress(82); this.categoriesList = this.newData.getAllCategories(); // Buscamos la categoria en la lista para coger el Identificador que tiene en nuestra base de datos para cada comando de nuestra lista for (int i = 0; i < commandsList.Count; i++) { cat = this.categoriesList.Find(category => (category.Name == commandsList[i].Cat.Name)); commandsList[i].Cat.Id_category = cat.Id_category; } worker.ReportProgress(84, Constantes.getMessage("ReportProgress_CCI")); // Insertamos los Comandos Iniciales en la Base de Datos modLog.Info("Cargamos los COMANDOS en la tabla COMMANDS"); if (!this.newData.chargeInitialCommands(this.commandsList, worker)) { throw new AppProcessException("InitialChargeErrorSavingCommands"); } modLog.Info("Comandos Iniciales Cargados en la Base de Datos"); }
protected override void doSpecificWork(BackgroundWorker worker, DoWorkEventArgs args) { Boolean result = false; String error = ""; try { this.modLog.Info("Borramos todos los usuarios y comandos usados en la base de datos, antes de cargar el fichero de logs que queremos analizar."); worker.ReportProgress(0, Constantes.getMessage("ReportProgress_LBD")); if (!this.chargeData.clearDataBase(worker)) { throw new AppProcessException("FileTreatmentErrorDeletingPreviousData"); } worker.ReportProgress(10, Constantes.getMessage("ReportProgress_CD")); this.modLog.Info("Cargamos los usuarios y comandos usados en la Base de Datos"); fileTreatment.treatFile(worker); this.modLog.Info("Fichero de Logs cargado correctamente en la Base de Datos"); result = true; } catch (AppProcessException ex) { result = false; this.modLog.Error(ex); error = ex.ExCode; } catch (Exception ex) { result = false; this.modLog.Error(ex); error = "WorkerErrorFileTreatment"; } finally { if (result) { worker.ReportProgress(100, Constantes.getMessage("ReportProgress_C1")); } else { throw new Exception(error); } } }
public static bool ReadDat(string fullname, long fileTimeStamp, BackgroundWorker bgw, out RvDat rvDat) { _bgw = bgw; rvDat = null; Console.WriteLine("Reading " + fullname); Stream fs; int errorCode = IO.FileStream.OpenFileRead(fullname, out fs); if (errorCode != 0) { _bgw.ReportProgress(0, new bgwShowError(fullname, errorCode + ": " + new Win32Exception(errorCode).Message)); return false; } StreamReader myfile = new StreamReader(fs, Program.Enc); string strLine = myfile.ReadLine(); myfile.Close(); fs.Close(); fs.Dispose(); if (strLine == null) return false; if (strLine.ToLower().IndexOf("xml", StringComparison.Ordinal) >= 0) { if (!ReadXMLDat(fullname, fileTimeStamp, out rvDat)) return false; } else if (strLine.ToLower().IndexOf("clrmamepro", StringComparison.Ordinal) >= 0 || strLine.ToLower().IndexOf("romvault", StringComparison.Ordinal) >= 0 || strLine.ToLower().IndexOf("game", StringComparison.Ordinal) >= 0) { if (!DatCmpReader.ReadDat(fullname, fileTimeStamp, out rvDat)) return false; } else if (strLine.ToLower().IndexOf("doscenter", StringComparison.Ordinal) >= 0) { // if (!DatDOSReader.ReadDat(datFullName)) // return; } else { _bgw.ReportProgress(0, new bgwShowError(fullname, "Invalid DAT File")); return false; } return true; }
private void BackgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { try { totalFileCount = Directory.GetFiles(Path, fileExtension, SearchOption.AllDirectories).Length; string[] files = Directory.GetFiles(Path, fileExtension, SearchOption.AllDirectories); foreach (var file in files) { processedFileCount++; var process = 100 / totalFileCount * processedFileCount; var hashstr = _hasher.GetHash(file); if (!dict.ContainsKey(hashstr)) { dict.Add(hashstr, file); } else { dupCount++; } backgroundWorker1.ReportProgress(process); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
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); }
//自定义函数 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); }
private void ConvertFiles(List <string> wavFiles) { //a list of files that may or may not exist. //create the int i = 0; foreach (string wavFile in wavFiles) { FileInfo wav = new FileInfo(wavFile); DirectoryInfo dir = wav.Directory; //create folder if neccessary string compressedFolder = string.Format(@"{0}\compressed-{1}", dir.Parent.FullName, dir.Name); if (Directory.Exists(compressedFolder) == false) { Directory.CreateDirectory(compressedFolder); } //convert file string mp3DestinationName = string.Format(@"{0}\{1}", compressedFolder, wav.Name.Replace(wav.Extension, ".mp3")); if (!File.Exists(mp3DestinationName)) { ConvertFile(wav.FullName, mp3DestinationName); } CompressWorker.ReportProgress(++i); } }
//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; }
public void BackgroundProcessing() { var entryThreadInfo = ThreadInfo.GetCurrentThreadInfo(); var worker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; worker.DoWork += (sender, e) => { var threadInfo = ThreadInfo.GetCurrentThreadInfo(); for (int i = 1; i <= 100; i++) { Thread.Sleep(50); worker.ReportProgress(i); } }; worker.ProgressChanged += (sender, e) => { Debug.WriteLine(e.ProgressPercentage); }; worker.RunWorkerCompleted += (sender, e) => { var threadInfo = ThreadInfo.GetCurrentThreadInfo(); }; worker.RunWorkerAsync(); }
private static void setFormat(string search, BackgroundWorker bw, string message, bool wildcards = true) { bw.ReportProgress(0, message); Object FindText = search; Object MatchCase = false; Object MatchWholeWord = false; Object MatchWildcards = wildcards; Object MatchSoundsLike = false; Object MatchAllWordForms = false; Object Forward = true; Object Wrap = WdFindWrap.wdFindStop; Object Format = false; Object ReplaceWith = null; Object Replace = WdReplace.wdReplaceNone; Globals.ThisAddIn.Application.Selection.HomeKey(WdUnits.wdStory); bool loop = true; while (loop) { Find findObject = Globals.ThisAddIn.Application.Selection.Find; findObject.ClearFormatting(); findObject.Replacement.ClearFormatting(); findObject.Font.Italic = 1; loop = findObject.Execute( ref FindText, ref MatchCase, ref MatchWholeWord, ref MatchWildcards, ref MatchSoundsLike, ref MatchAllWordForms, ref Forward, ref Wrap, ref Format, ref ReplaceWith, ref Replace ); Globals.ThisAddIn.Application.Selection.Font.Italic = 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; }
protected void RecursiveCopy(string origin, string destination, BackgroundWorker worker) { try { List<string> fileContents = new List<string>(Directory.GetFiles(origin)); foreach (var file in fileContents) { File.Copy(file, destination + Path.DirectorySeparatorChar + Path.GetFileName(file)); this.CurrentCopiedSize += new FileInfo(file).Length; worker.ReportProgress(0, "Copied " + file); } List<string> dirContents = new List<string>(Directory.GetDirectories(origin)); foreach (var dir in dirContents) { worker.ReportProgress(0, "Copying Dir:" + dir); String copiedDirPath = destination + Path.DirectorySeparatorChar + dir.Split(Path.DirectorySeparatorChar).Last(); Directory.CreateDirectory(copiedDirPath); this.RecursiveCopy(dir, copiedDirPath, worker); } } catch (Exception e) { UpdateHistory(e.Message); } }
public unsafe Bitmap ToBitmap(BackgroundWorker worker) { var pixels = this.To32BppArray(); Bitmap bitmap = new Bitmap(pixels.GetUpperBound(1) + 1, pixels.GetUpperBound(0) + 1, PixelFormat.Format24bppRgb); BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int stride = data.Stride; byte[] bytes = new byte[stride * bitmap.Height]; for (int r = 0; r < bitmap.Height; r++) { for (int c = 0; c < bitmap.Width; c++) { Color color = Color.FromArgb(pixels[r, c]); bytes[(r * stride) + c * 3] = color.B; bytes[(r * stride) + c * 3 + 1] = color.G; bytes[(r * stride) + c * 3 + 2] = color.R; } if (worker.CancellationPending) { break; } worker.ReportProgress((int)(((decimal)r / (decimal)bitmap.Height) * 100m)); } IntPtr scan0 = data.Scan0; Marshal.Copy(bytes, 0, scan0, stride * bitmap.Height); bitmap.UnlockBits(data); return bitmap; }
private void bgwMD5_DoWork(object sender, DoWorkEventArgs e) { string filePath = e.Argument.ToString(); byte[] buffer; int bytesRead; long sizeOfFile, totalBytesToRead = 0; using (Stream fileStream = File.OpenRead(filePath)) { sizeOfFile = fileStream.Length; using (HashAlgorithm md5 = MD5.Create()) { do { buffer = new byte[4096]; bytesRead = fileStream.Read(buffer, 0, buffer.Length); totalBytesToRead += bytesRead; md5.TransformBlock(buffer, 0, bytesRead, null, 0); bgwMD5.ReportProgress((int)((double)totalBytesToRead / sizeOfFile * 100)); } while (bytesRead != 0); md5.TransformFinalBlock(buffer, 0, 0); e.Result = MakeMD5HashString(md5.Hash); } } }
public MainWindow() { InitializeComponent(); worker = new BackgroundWorker(); // ProgressChangedイベントを発生させるようにする worker.WorkerReportsProgress = true; // RunWorkerAsyncメソッドで呼ばれるDoWorkに、 // 別スレッドでUSBカメラの画像を取得し続けるイベントハンドラを追加 worker.DoWork += (sender, e) => { using (var capture = Cv.CreateCameraCapture(0)) { IplImage frame; while (true) { frame = Cv.QueryFrame(capture); // 新しい画像を取得したので、 // ReportProgressメソッドを使って、ProgressChangedイベントを発生させる worker.ReportProgress(0, frame); } } }; // ReportProgressメソッドで呼ばれるProgressChangedのイベントハンドラを追加 worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged); }
protected internal void ReportProgress(BackgroundWorker background, int progress, ProgressChangedArgs args) { updating = true; background.ReportProgress(progress, args); while (updating) ; }
public void ReportProgressNonBusy () { BackgroundWorker b = new BackgroundWorker (); b.WorkerReportsProgress = true; Assert.IsFalse (b.IsBusy, "#1"); b.ReportProgress (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 { } }
private void CountdownClock_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { while (!workerdone && (minutes != 0 || seconds != 0 || miliseconds != 0)) { if (miliseconds == 0) { if (seconds == 0) { if (minutes != 0) { minutes--; seconds = 59; miliseconds = 59; } } else { seconds--; miliseconds = 59; } } else { miliseconds--; } CountdownClock.ReportProgress(1, minutes.ToString("0") + " : " + seconds.ToString("00") + " : " + miliseconds.ToString("00")); System.Threading.Thread.Sleep(17); } }
private void bw_DoWork(object sender, DoWorkEventArgs e) { bw.ReportProgress(0); int numTrials = Int32.Parse(txtNumTrials.Text); optimizer.Optimize(numTrials); e.Result = optimizer.OptimalSeatingPlan; }
private void BgWorker1_DoWork(object sender, DoWorkEventArgs e) { do { // InitPerformanceCounters method sends events to the backgroundWorker1_ProgressChanged method TaskManagerLib.GetProcesses(out Process[] procArray); int procsAdded = TaskManagerLib.AddNewProcesses(ref procList, procArray, excludedProcesses); if (procsAdded > 0) { bgWorker1.ReportProgress(1); } Console.WriteLine($"Processes added : {procsAdded}"); int valsUpdated = TaskManagerLib.UpdateValues(ref procList); if (valsUpdated > 0) { bgWorker1.ReportProgress(1); } Console.WriteLine($"Processes Updated : {valsUpdated}"); int procsRemoved = TaskManagerLib.RemoveDeadProcesses(ref procList, procArray); if (procsRemoved > 0) { bgWorker1.ReportProgress(1); } Console.WriteLine($"Processes removed : {procsRemoved}"); // use Task.Delay to avoid blocking Task.Delay(1200).Wait(); }while (true); }
void Info(int cnt, bool worker, string key, string info, ResultDataClass data = null) { if (worker) { measWorker.ReportProgress(cnt, new ReportDataClass(key, info, data)); } else { if ((key == InfoLine) || (key == ControlLine)) { nf.AddToINFO(info, key); } else if ((key == DataLine) && (data != null)) { nf.AddToINFO(info, key, data); } } }
private FullSpriteSet(IList <AbstractSprite> sprites, System.ComponentModel.BackgroundWorker worker, int tasksComplete, int tasks) { bool haveWorker = worker != null; if (haveWorker) { worker.ReportProgress((tasksComplete++ *100) / tasks, "Sorting"); } sprites.Sort((a, b) => a.Name.CompareTo(b.Name)); this.sprites = sprites; }
private void bgWorker_DoWork(object sender, DoWorkEventArgs e) { for (int i = 1; i <= 100; i++) { if (bgWorker.CancellationPending) { e.Cancel = true; break; } Thread.Sleep(300); bgWorker.ReportProgress(i); } }
private FullSpriteSet(IList <AbstractSprite> sprites, System.ComponentModel.BackgroundWorker worker, int tasksComplete, int tasks) { bool haveWorker = worker != null; if (haveWorker) { worker.ReportProgress((tasksComplete++ *100) / tasks, "Sorting"); } sprites.Sort((a, b) => a.Name.CompareTo(b.Name)); this.sprites = sprites; Thumbnails = new ImageList(); Thumbnails.ImageSize = new System.Drawing.Size(80, 48); foreach (var sprite in sprites) { if (haveWorker) { worker.ReportProgress((tasksComplete++ *100) / tasks, string.Format("Generating thumbnail for {0}", sprite.Name)); } Thumbnails.Images.Add(sprite.Name, sprite.GetThumbnail()); } }
/// <summary> /// This method is called when changes are done to a file /// <para>Counts the number of changes already done by the sync framework</para> /// <para>Reports the progress percentage to the backgroundWorkerForSync</para> /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnAppliedChange(object sender, AppliedChangeEventArgs args) { if ((agent.State == SyncOrchestratorState.Downloading || agent.State == SyncOrchestratorState.Uploading || agent.State == SyncOrchestratorState.UploadingAndDownloading) && backgroundWorkerForSync.CancellationPending) { agent.Cancel(); } countDoneChanges++; // This method will raise an event to the backgroundWorkerForSync via backgroundWorkerForSync_ProgressChanged backgroundWorkerForSync.ReportProgress((int)((double)countDoneChanges / countChanges * 100)); }
private void ReportProgress(int downloadedBytes, int totalBytes) { this.bytesDone = downloadedBytes; this.bytesTotal = totalBytes; if (FWorker != null) { if (totalBytes != 0) { FWorker.ReportProgress(Convert.ToInt32(downloadedBytes * 100 / totalBytes), this); } } }
// This is the method that does the actual work. For this // example, it computes a Fibonacci number and // reports progress as it does its work. long ComputeFibonacci(int n, System.ComponentModel.BackgroundWorker worker, DoWorkEventArgs e) { // The parameter n must be >= 0 and <= 91. // Fib(n), with n > 91, overflows a long. if ((n < 0) || (n > 91)) { throw new ArgumentException( "value must be >= 0 and <= 91", "n"); } long result = 0; // Abort the operation if the user has canceled. // Note that a call to CancelAsync may have set // CancellationPending to true just after the // last invocation of this method exits, so this // code will not have the opportunity to set the // DoWorkEventArgs.Cancel flag to true. This means // that RunWorkerCompletedEventArgs.Cancelled will // not be set to true in your RunWorkerCompleted // event handler. This is a race condition. if (worker.CancellationPending) { e.Cancel = true; } else { if (n < 2) { result = 1; } else { result = ComputeFibonacci(n - 1, worker, e) + ComputeFibonacci(n - 2, worker, e); } // Report progress as a percentage of the total task. int percentComplete = (int)((float)n / (float)numberToCompute * 100); if (percentComplete > highestPercentageReached) { highestPercentageReached = percentComplete; worker.ReportProgress(percentComplete); } } return(result); }
public void bgWork_DoWork(Object sender, DoWorkEventArgs e) { #if DEBUG sout.println("FormGenerateKeySound#bgWork_DoWork"); #endif PrepareStartArgument arg = (PrepareStartArgument)e.Argument; string singer = arg.singer; double amp = arg.amplitude; string dir = arg.directory; bool replace = arg.replace; // 音源を準備 if (!Directory.Exists(dir)) { PortUtil.createDirectory(dir); } for (int i = 0; i < 127; i++) { string path = Path.Combine(dir, i + ".wav"); sout.println("writing \"" + path + "\" ..."); if (replace || (!replace && !File.Exists(path))) { try { GenerateSinglePhone(i, singer, path, amp); if (File.Exists(path)) { try { Wave wv = new Wave(path); wv.trimSilence(); wv.monoralize(); wv.write(path); } catch (Exception ex0) { serr.println("FormGenerateKeySound#bgWork_DoWork; ex0=" + ex0); Logger.write(typeof(FormGenerateKeySound) + ".bgWork_DoWork; ex=" + ex0 + "\n"); } } } catch (Exception ex) { Logger.write(typeof(FormGenerateKeySound) + ".bgWork_DoWork; ex=" + ex + "\n"); serr.println("FormGenerateKeySound#bgWork_DoWork; ex=" + ex); } } sout.println(" done"); if (m_cancel_required) { m_cancel_required = false; break; } bgWork.ReportProgress((int)(i / 127.0 * 100.0), null); } m_cancel_required = false; }
private void backgroundWriter_DoWork(object sender, DoWorkEventArgs e) { byte[] tempDataBuffer = new byte[128]; ushort i = 0; bool lastStatus = false; //Write all required frames of the Memory Card while (i < maxWritingFrames) { //Check if the "Abort" button has been pressed if (backgroundWriter.CancellationPending == true) { return; } //Get 128 byte frame data Array.Copy(completeMemoryCard, i * 128, tempDataBuffer, 0, 128); //Reset write status lastStatus = false; //Write data to DexDrive if (currentDeviceIdentifier == 0) { lastStatus = dexDevice.WriteMemoryCardFrame(i, tempDataBuffer); } //Write data to MemCARDuino if (currentDeviceIdentifier == 1) { lastStatus = CARDuino.WriteMemoryCardFrame(i, tempDataBuffer); } //Write data to PS1CardLink if (currentDeviceIdentifier == 2) { lastStatus = PS1CLnk.WriteMemoryCardFrame(i, tempDataBuffer); } //Check if there was a frame or checksum mismatch if (lastStatus == true) { backgroundWriter.ReportProgress(i); i++; } } //All data has been written, report success sucessfullRead = true; }
/// <summary> /// 主要工作逻辑 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void worker_DoWork(object sender, DoWorkEventArgs e) { System.ComponentModel.BackgroundWorker tempWorker = sender as System.ComponentModel.BackgroundWorker; for (int i = 0; i <= 100; i++) { if (tempWorker.CancellationPending) //当点击Cancel按钮时,CancellationPending被设置为true { e.Cancel = true; //此处设置Cancel=true后,就可以在RunWorkerCompleted中判断e.Cancelled是否为true break; } Thread.Sleep(200); //避免太快,让线程暂停一会再报告进度 tempWorker.ReportProgress(i); //调用ReportProgress()方法报告进度,同时触发ProgressChanged事件 } }
private void bgwZeroOutInvNeg_DoWork(object sender, DoWorkEventArgs e) { try { mstStatus = "Connecting to database..."; bgwZeroOutInvNeg.ReportProgress(10); AceSoft.RetailPlus.Client.MasterDB clsMasterConnection = new AceSoft.RetailPlus.Client.MasterDB(); clsMasterConnection.GetConnection(); mstStatus = "Updating product negative quantity to zero..."; bgwZeroOutInvNeg.ReportProgress(20); Data.ProductInventories clsProductInventories = new Data.ProductInventories(clsMasterConnection.Connection, clsMasterConnection.Transaction); clsProductInventories.ZeroOutNegativeInventorygByBranch(mclsBranchDetails.BranchID); mstStatus = "Commiting to database..."; bgwZeroOutInvNeg.ReportProgress(90); clsMasterConnection.CommitAndDispose(); bgwZeroOutInvNeg.ReportProgress(100); } catch { throw; } }
/// <summary> /// Updates the dialog's progress bar. /// </summary> /// <param name="percentProgress">The percentage, from 0 to 100, of the operation that is complete.</param> /// <param name="text">The new value of the progress dialog's primary text message, or <see langword="null"/> to leave the value unchanged.</param> /// <param name="description">The new value of the progress dialog's additional description message, or <see langword="null"/> to leave the value unchanged.</param> /// <param name="userState">A state object that will be passed to the <see cref="ProgressChanged"/> event handler.</param> /// <remarks>Call this method from the <see cref="DoWork"/> event handler if you want to report progress.</remarks> /// <exception cref="ArgumentOutOfRangeException"><paramref name="percentProgress"/> is out of range.</exception> /// <exception cref="InvalidOperationException">The progress dialog is not currently being displayed.</exception> public void ReportProgress(int percentProgress, string text, string description, object userState) { if (percentProgress < 0 || percentProgress > 100) { throw new ArgumentOutOfRangeException("percentProgress"); } if (_dialog == null) { throw new InvalidOperationException(Properties.Resources.ProgressDialogNotRunningError); } _backgroundWorker.ReportProgress(percentProgress, new ProgressChangedData() { Text = text, Description = description, UserState = userState }); }
public void SaveFile(string SVFile, List <string> Data, System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e) { CurrentState state = new CurrentState(); int counter = 0; string TextSent = ""; string tempTxt = ""; // SVFile.DefaultExt = ".txt"; using (System.IO.StreamWriter file = new System.IO.StreamWriter(SVFile, false)) { for (int y = 0; y <= Data.Count - 1;) { if ((worker.CancellationPending == true)) { e.Cancel = true; worker.Dispose(); worker = null; GC.Collect(); MessageBox.Show("Canceled"); break; } TextSent = ""; for (int x = 0; x <= columns - 1; x++) { if (x + y != Data.Count) { TextSent += Data[y + x] + " "; } } TextSent = Data[y] + " " + Data[y + 1] + " " + Data[y + 2] + " " + Data[y + 3] + " " + Data[y + 4] + " " + Data[y + 5] + " " + Data[y + 6] + " " + Data[y + 7] + " " + Data[y + 8] + " " + Data[y + 9] + " " + Data[y + 10]; file.WriteLine(TextSent); y += columns; counter++; if (counter % 100 == 0) { state.LinesCounted = counter; state.DataStorage = Data; worker.ReportProgress(0, state); } } } if (worker != null) { MessageBox.Show("Finished saving the file."); } }
void worker_DoWork(object sender, DoWorkEventArgs e) { string argument = e.Argument as string; _exit_flag = false; switch (argument) { case "ACTION_START": { this.TaskUpdateData(TaskStatus.TASK_RUNNING); this.TaskRunningRecord(TaskRunningList.TASK_DOCUMENT); worker.ReportProgress(1); this.setTaskTimer(_finishTime); this.initPPT(); int pageNum = 1; try { do { if (this.workerCancelCheck(e) == true) { return; } this.addPage(pageNum); //pageNum++; Thread.Sleep(2000); } while (this._exit_flag == false); }catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("Full Stacktrace: {0}", ex.ToString())); } break; } case "ACTION_END": { break; } } }
private void bgrwLoadSeries_DoWork(object sender, DoWorkEventArgs e) { List <string> filePaths = (List <string>)e.Argument; int count = 0; foreach (string filePath in filePaths) { count++; DicomElement currentDicomElement = new DicomElement(filePath); this.CurrentDicomImageViewControl.DicomElements.Add(currentDicomElement); this.CurrentDicomImageViewControl.DicomElements.Sort(); bgrwLoadSeries.ReportProgress(count); } this.CurrentDicomImageViewControl.CurrentDicomElement = this.CurrentDicomImageViewControl.DicomElements[0]; }
void worker_DoWork(object sender, DoWorkEventArgs e) { string argument = e.Argument as string; this._exit_flag = false; switch (argument) { case "ACTION_START": { this.TaskUpdateData(TaskStatus.TASK_RUNNING); this.TaskRunningRecord(TaskRunningList.TASK_MEDIAPLAYER); worker.ReportProgress(1); //View Update playVideo(_filepath); try { do { //worker cancel check if (this.workerCancelCheck(e) == true) { return; } } while (this._exit_flag == false); }catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("Full Stacktrace: {0}", ex.ToString())); } break; } case "ACTION_END": { System.Diagnostics.Debug.WriteLine(string.Format("WMP ACTION END")); break; } default: break; } }