public WorkerReturn NumberOfFiles( WorkerArgs args, BackgroundWorker worker ) { long bytes = 0; long byteCount = 0; var retVal = new WorkerReturn(); StreamReader reader = null; try { var fi = new FileInfo(args.InputFile); bytes = fi.Length; reader = fi.OpenText(); if ( args.HasHeaders ) { byteCount += reader.ReadLine().Length; } while ( !worker.CancellationPending && !reader.EndOfStream ) { byteCount += reader.ReadLine().Length; retVal.NumberOfInputLines++; if ( retVal.NumberOfInputLines % 10000 == 0 ) { double percent = byteCount * 100.0 / bytes; worker.ReportProgress((int)percent); } } } finally { if ( reader != null ) { reader.Close(); reader.Dispose(); } retVal.NumberOfFiles = (int)Math.Ceiling((double)retVal.NumberOfInputLines/args.NumberOfLinesPerFile); } return retVal; }
private void bApply_Click(object sender, EventArgs e) { if (cbDisableLive.Checked) { bXliveSettings.Enabled = true; } var args = new WorkerArgs(); args.xlive = cbDisableLive.Checked; //args.stripedids=cbStripGeck.Checked; //args.striprefs=cbRemoveClutter.Checked; args.trimbsa = cbShrinkTextures.Checked; args.hwnd = Handle; tbDescription.Text = ""; bApply.Enabled = false; bReset.Enabled = true; lines = new string[70]; for (var i = 0; i < 70; i++) { lines[i] = string.Empty; } LineCount = 0; backgroundWorker1.RunWorkerAsync(args); }
/// <summary>Calls the OnWorkFinishedHandler</summary> /// <param name="args">The range that is passed to the OnWorkFinishedHandler</param> private void CallOnWorkFinishedHandler(WorkerArgs args) { if(onWorkFinishedHandler != null) onWorkFinishedHandler(this, args); }
private static void ActionWorkerDoWork(object sender, DoWorkEventArgs e) { const int progressBufferSize = 5; BackgroundWorker worker = (BackgroundWorker)sender; WorkerArgs args = (WorkerArgs)e.Argument; string[] allFiles = Directory.GetFiles(args.BaseDirectory, "*.*", args.IncludeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); WorkerProgress[] progressBuffer = new WorkerProgress[progressBufferSize]; int reportBufferCounter = 1; IEnumerable <Regex> maskPatterns = GenerateMaskPatterns(args.FileMasks); for (int i = 0; i < allFiles.Length; i++) { if (worker.CancellationPending) { e.Cancel = true; break; } string path = allFiles[i]; string fileName = Path.GetFileName(path); if (!SatisfiesMaskPatterns(fileName, maskPatterns)) { continue; } Encoding encoding = TextEncoding.GetFileEncoding(path); string charset = encoding?.WebName ?? "(Unknown)"; if (args.Action == CurrentAction.Validate) { if (args.ValidCharsets.Contains(charset)) { continue; } } string directoryName = Path.GetDirectoryName(path); progressBuffer[reportBufferCounter - 1] = new WorkerProgress { Charset = charset, FileName = fileName, DirectoryName = directoryName }; reportBufferCounter++; if (reportBufferCounter > progressBufferSize) { reportBufferCounter = 1; int percentageCompleted = (i * 100) / allFiles.Length; WorkerProgress[] reportProgress = new WorkerProgress[progressBufferSize]; Array.Copy(progressBuffer, reportProgress, progressBufferSize); worker.ReportProgress(percentageCompleted, reportProgress); Array.Clear(progressBuffer, 0, progressBufferSize); } } // Copy remaining results from buffer, if any. if (reportBufferCounter > 1) { reportBufferCounter--; int percentageCompleted = 100; WorkerProgress[] reportProgress = new WorkerProgress[reportBufferCounter]; Array.Copy(progressBuffer, reportProgress, reportBufferCounter); worker.ReportProgress(percentageCompleted, reportProgress); Array.Clear(progressBuffer, 0, reportBufferCounter); } }
public void Work(WorkerArgs job) { DidWork = true; }
protected override void DoWork(DoWorkEventArgs e) { WorkerArgs args = e.Argument as WorkerArgs; if (args != null) { var dataModel = Repository.DataModel; List <Recipient> recipients = new List <Recipient>(); if (args.AllCERSBizLeadUsersForBizWithAtLeastFiveFacilities) { recipients.AddRange((from q in dataModel.OrganizationContactRoleWithFacilityCounts where q.FacilityCount >= 5 && q.RoleName == "OrgAdmin" select new Recipient { Email = q.Email, ContactID = q.ContactID, FullName = q.FullName }).ToList().Distinct(new RecipientEmailEqualityComparer()) ); } else { recipients.AddRange((from q in dataModel.OrganizationContactRoleWithFacilityCounts where q.RoleName == "OrgAdmin" select new Recipient { Email = q.Email, ContactID = q.ContactID, FullName = q.FullName }).ToList().Distinct(new RecipientEmailEqualityComparer()) ); } if (!string.IsNullOrWhiteSpace(args.ToCustomAddresses)) { string[] customRecipients = tbToCustomAddressList.Text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (customRecipients.Length > 0) { recipients.AddRange((from c in customRecipients select new Recipient { Email = c }).Distinct(new RecipientEmailEqualityComparer()) ); } } //make sure we really are dealing with unique email addresses recipients = recipients.Distinct(new RecipientEmailEqualityComparer()).ToList(); bool debugMode = args.DebugMode; NotifyMessageFromThread("Found " + recipients.Count + " recipients to notify."); int total = recipients.Count; int index = 0; string targetRecipientEmail = string.Empty; foreach (var recipient in recipients) { index++; targetRecipientEmail = recipient.Email; if (debugMode) { targetRecipientEmail = "*****@*****.**"; } NotifyMessageFromThread("Sending " + index + " of " + total + ": " + recipient.Email + (debugMode ? "(debug: " + targetRecipientEmail + ") " : "")); Services.Emails.Send(targetRecipientEmail, args.Subject, args.Body, args.Priority, args.HTMLEmail, contactID: recipient.ContactID); CalculateAndReportWorkerProgress(index, total); } } }
private static void ActionWorkerDoWork(object sender, DoWorkEventArgs e) { const int progressBufferSize = 5; BackgroundWorker worker = (BackgroundWorker)sender; WorkerArgs args = (WorkerArgs)e.Argument; string[] allFiles = Directory.GetFiles(args.BaseDirectory, "*.*", args.IncludeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); WorkerProgress[] progressBuffer = new WorkerProgress[progressBufferSize]; int reportBufferCounter = 1; IEnumerable <Regex> maskPatterns = GenerateMaskPatterns(args.FileMasks); for (int i = 0; i < allFiles.Length; i++) { if (worker.CancellationPending) { e.Cancel = true; break; } string path = allFiles[i]; string fileName = Path.GetFileName(path); if (!SatisfiesMaskPatterns(fileName, maskPatterns)) { continue; } CharsetDetector detector = new CharsetDetector(); using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { detector.Feed(fs); detector.DataEnd(); } if (args.Action == CurrentAction.Validate) { if (detector.Charset == null) { continue; } if (args.ValidCharsets.Contains(detector.Charset)) { continue; } } string directoryName = Path.GetDirectoryName(path); WorkerProgress progress = new WorkerProgress(); progress.Charset = detector.Charset ?? "(Unknown)"; progress.FileName = fileName; progress.DirectoryName = directoryName; progressBuffer[reportBufferCounter - 1] = progress; reportBufferCounter++; if (reportBufferCounter > progressBufferSize) { reportBufferCounter = 1; int percentageCompleted = (i * 100) / allFiles.Length; WorkerProgress[] reportProgress = new WorkerProgress[progressBufferSize]; Array.Copy(progressBuffer, reportProgress, progressBufferSize); worker.ReportProgress(percentageCompleted, reportProgress); Array.Clear(progressBuffer, 0, progressBufferSize); } } }
/// <summary> /// 初始化异步任务 /// </summary> private void initWorker(QueryMode queryMode) { worker = new BackgroundWorker(); worker.WorkerSupportsCancellation = true; worker.WorkerReportsProgress = true; TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Normal; worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged); WorkerArgs args = new WorkerArgs() { Url = baseUrl ,SelectedClassIndex = selectedClass.SelectedIndex}; if (queryMode == QueryMode.SiglePersonSigleClass) { if (string.IsNullOrEmpty(stuidTextBox.Text) && string.IsNullOrEmpty(stuNameTextBox.Text)) { MessageBox.Show("先输入学生id或者姓名"); return; } if(!string.IsNullOrEmpty(stuidTextBox.Text)) { args.StudentId = stuidTextBox.Text;//学生id } if (!string.IsNullOrEmpty(stuNameTextBox.Text)) { args.StudentName = stuNameTextBox.Text;//学生姓名 } worker.DoWork += new DoWorkEventHandler(worker_DoWork_单人单科); } else if (queryMode == QueryMode.SiglePersonMultiClass) { if (string.IsNullOrEmpty(stuidTextBox.Text) && string.IsNullOrEmpty(stuNameTextBox.Text)) { MessageBox.Show("先输入学生id或者姓名"); return; } if (!string.IsNullOrEmpty(stuidTextBox.Text)) { args.StudentId = stuidTextBox.Text;//学生id } if (!string.IsNullOrEmpty(stuNameTextBox.Text)) { args.StudentName = stuNameTextBox.Text;//学生姓名 } worker.DoWork += new DoWorkEventHandler(worker_DoWork_单人多科); } else if (queryMode == QueryMode.MultiPersonSingleClass) { if (!string.IsNullOrEmpty(stuNo_start_TextBox.Text) && !string.IsNullOrEmpty(stuNo_end_TextBox.Text)) { args.StudentStartNo = stuNo_start_TextBox.Text; args.StudentEndNo = stuNo_end_TextBox.Text; args.isStudentNoRangeValid = true; } else if (!string.IsNullOrEmpty(stuid_start_TextBox.Text) && !string.IsNullOrEmpty(stuid_end_TextBox.Text)) { args.StudentStartId = stuid_start_TextBox.Text; args.StudentEndId = stuid_end_TextBox.Text; args.isStudentNoRangeValid = false; } else { MessageBox.Show("先输入学号范围或者学生id范围"); return; } worker.DoWork += new DoWorkEventHandler(worker_DoWork_多人单科); } else if (queryMode == QueryMode.加权平均分) { if (!string.IsNullOrEmpty(stuNo_start_TextBox.Text) && !string.IsNullOrEmpty(stuNo_end_TextBox.Text)) { args.StudentStartNo = stuNo_start_TextBox.Text; args.StudentEndNo = stuNo_end_TextBox.Text; args.isStudentNoRangeValid = true; } else if (!string.IsNullOrEmpty(stuid_start_TextBox.Text) && !string.IsNullOrEmpty(stuid_end_TextBox.Text)) { args.StudentStartId = stuid_start_TextBox.Text; args.StudentEndId = stuid_end_TextBox.Text; args.isStudentNoRangeValid = false; } else { MessageBox.Show("先输入学号范围或者学生id范围"); return; } worker.DoWork += new DoWorkEventHandler(worker_DoWork_加权平均); } args.QueryMode = queryMode; worker.RunWorkerAsync(args); QueryBtn.IsEnabled = false; QueryBtn.Content = "正在查询..."; }
private void StartAction(CurrentAction action) { string directory = lstBaseDirectory.Text; if (string.IsNullOrEmpty(directory)) { ShowWarning("Please specify a directory to check"); return; } if (!Directory.Exists(directory)) { ShowWarning("The directory you specified '{0}' does not exist", directory); return; } if (action == CurrentAction.Validate && lstValidCharsets.CheckedItems.Count == 0) { ShowWarning("Select one or more valid character sets to proceed with validation"); return; } _currentAction = action; _settings.RecentDirectories.Add(directory); UpdateControlsOnActionStart(action); List<string> validCharsets = new List<string>(lstValidCharsets.CheckedItems.Count); foreach (string validCharset in lstValidCharsets.CheckedItems) validCharsets.Add(validCharset); WorkerArgs args = new WorkerArgs(); args.Action = action; args.BaseDirectory = directory; args.IncludeSubdirectories = chkIncludeSubdirectories.Checked; args.FileMasks = txtFileMasks.Text; args.ValidCharsets = validCharsets; _actionWorker.RunWorkerAsync(args); }
private void worker_DoWork(object sender, DoWorkEventArgs e) { WorkerArgs args = e.Argument as WorkerArgs; var con = args.Connection; var dir = new DirectoryInfo(args.ExportPath); using (new CultureScope(CultureInfo.InvariantCulture)) using (con) { con.Open(); var schema = con.GetSchema("Tables"); Dictionary <string, List <string> > tables = new Dictionary <string, List <string> >(); //List<string> tables = new List<string>(); foreach (DataRow item in schema.Rows) { if (item[3].Equals("BASE TABLE")) { string schemaName = item[1] as string; string name = item[2] as string; if (!tables.ContainsKey(schemaName)) { tables.Add(schemaName, new List <string>()); } tables[schemaName].Add(name); } } foreach (var schemaName in tables.Keys) { for (int j = 0; j < tables[schemaName].Count; j++) { int rowCount = 0; string name = tables[schemaName][j]; using (DbCommand cmd = con.CreateCommand()) { cmd.CommandText = string.Format("SELECT * FROM [{0}].[{1}]", schemaName, name); cmd.CommandType = CommandType.Text; FileInfo file = new FileInfo(Path.Combine(dir.FullName, string.Format("{0}.csv", name))); if (!dir.Exists) { dir.Create(); } using (DbDataReader reader = cmd.ExecuteReader()) using (StreamWriter sw = new StreamWriter(file.Open(FileMode.Create, FileAccess.Write, FileShare.None))) { int fieldCount = reader.FieldCount; string[] fieldNames = new string[fieldCount]; Func <object, string>[] serializers = new Func <object, string> [fieldCount]; bool[] typeNeedQuote = new bool[fieldCount]; for (int i = 0; i < fieldCount; i++) { fieldNames[i] = reader.GetName(i); Type fieldType = reader.GetFieldType(i); if (fieldType == typeof(Byte[])) { serializers[i] = BinarySerializer; typeNeedQuote[i] = false; } else if (fieldType == typeof(string) | (fieldType == typeof(Guid))) { serializers[i] = DefaultSerializer; typeNeedQuote[i] = true; } else { // Default serializer serializers[i] = DefaultSerializer; typeNeedQuote[i] = false; } } sw.WriteLine(string.Join(",", fieldNames)); object[] values = new object[fieldCount]; string[] serializedValues = new string[fieldCount]; bool[] addQuote = new bool[fieldCount]; while (reader.Read()) { rowCount++; reader.GetValues(values); for (int i = 0; i < fieldCount; i++) { object value = values[i]; // Check if null if (value == null || value is DBNull) { addQuote[i] = false; serializedValues[i] = ""; } else { addQuote[i] = typeNeedQuote[i]; serializedValues[i] = serializers[i](value); } } { int i = 0; for (; i < fieldCount - 1; i++) { AppendField(sw, serializedValues[i], addQuote[i]); sw.Write(','); } AppendField(sw, serializedValues[i], addQuote[i]); sw.WriteLine(); } } // DataReader is finished } // Remove Empty file if (rowCount == 0) { file.Delete(); } // Command is finished } this.worker.ReportProgress((int)((j + 1) * 100.0 / tables[schemaName].Count)); // Table is finished } } // All table finished } // Connection is closed }
private void Export(object arg) { ProviderViewModel provider = this.SelectedProvider; if (provider == null) { return; } var factory = provider.GetProviderFactory(); var connection = factory.CreateConnection(); connection.ConnectionString = this.ConnectionStringBuilder.ConnectionString; WorkerArgs args = new WorkerArgs() { Connection = connection, ExportPath = this.ExportPath }; this.worker.RunWorkerAsync(args); }
public int SplitFile( WorkerArgs args, BackgroundWorker worker ) { StreamReader reader = null; int result = 0; int lineCount = 0; try { reader = File.OpenText(args.InputFile); StreamWriter writer = null; string openedFileName = null; string headers = null; while ( !worker.CancellationPending && !reader.EndOfStream ) { if ( lineCount % args.LinesPerFile == 0 ) { CloseOutputFile(writer); writer = OpenOutputFile(args.OutputFile, ++result, out openedFileName); if ( headers != null ) { writer.WriteLine(headers); } } if ( lineCount % 10000 == 0 ) { double percentage = lineCount * 100.0 / args.TotalLines; worker.ReportProgress((int)percentage); } var line = reader.ReadLine(); if ( lineCount == 0 ) { if ( args.FirstLineIsHeaders ) { headers = line; } } writer.WriteLine(line); lineCount++; } if ( writer != null ) { CloseOutputFile(writer); if ( lineCount == 0 && openedFileName != null ) { File.Delete(openedFileName); } } } catch { result = 0; } finally { if ( reader != null ) { reader.Close(); reader.Dispose(); } } return result; }
private void restartWorker() { Util.Init(); var args = new WorkerArgs(); args.runOverlay = OverlayEnabled.IsChecked.Value; args.runBot = BotEnabled.IsChecked.Value; if (backgroundWorker.IsBusy) backgroundWorker.CancelAsync(); else backgroundWorker.RunWorkerAsync(args); }
private void WriteMkvTags(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; WorkerArgs args = e.Argument as WorkerArgs; DirectoryInfo di = new DirectoryInfo(args.Directory); List <FileInfo> mkvFiles = new List <FileInfo>(); mkvFiles.AddRange(di.GetFiles("*.mkv", SearchOption.AllDirectories)); mkvFiles.AddRange(di.GetFiles("*.mk3d", SearchOption.AllDirectories)); MPTVSeriesImporter importer = new MPTVSeriesImporter(); importer.OpenConnection(); int current = 0; int total = mkvFiles.Count; foreach (FileInfo mkvFile in mkvFiles) { string file = mkvFile.FullName; if (worker.CancellationPending) { e.Cancel = true; break; } current++; worker.ReportProgress(100 * current / total); // init document MatroskaTags tag = new MatroskaTags(); // Read MKV tags, if existing should be reused if (App.Config.BasedOnExistingTags) { tag = MatroskaLoader.ReadTag(file); } // update tags from MP-TVSeries tag.Series = importer.UpdateTags(tag.Series, file); try { int exitCode = MatroskaLoader.WriteTagToMatroska(mkvFile.FullName, tag); if (exitCode == 0) { worker.ReportProgress(100 * current / total, new FileBasedLogEntry(mkvFile.FullName, "MKV updated: ")); if (args.DeleteXmlAfterMkvUpdate) { // build xml file name string xmlFile = GetXmlFilename(file); File.Delete(xmlFile); } } else { worker.ReportProgress(100 * current / total, new FileBasedLogEntry(mkvFile.FullName, string.Format( "MKV updated with MKVPropEdit exit code = {0} file :", exitCode))); } } catch (Exception ex) { worker.ReportProgress(100 * current / total, new FileBasedLogEntry(mkvFile.FullName, ex.Message)); } } importer.CloseConnection(); }
void _worker_DoWork(object sender, DoWorkEventArgs e) { WorkerArgs args = (e.Argument as WorkerArgs); if (args == null) { return; } int serverIndex = 0; System.Collections.Concurrent.ConcurrentQueue <LaunchItem> globalQueue = args.ConcurrentLaunchQueue; int serverTotal = globalQueue.Count; if (serverTotal == 0) { return; } LaunchItem launchItem = null; var accountLaunchTimes = _gameSessionMap.GetLaunchAccountTimes(); while (globalQueue.TryDequeue(out launchItem)) { LaunchManager mgr = new LaunchManager(_launcherLocation, launchItem, accountLaunchTimes); mgr.ReportStatusEvent += (status, item) => HandleLaunchMgrStatus(status, item, serverIndex, serverTotal); LaunchManager.LaunchManagerResult launchResult; GameSession session = null; try { session = _gameSessionMap.StartLaunchingSession(launchItem.ServerName, launchItem.AccountName); UpdateAccountStatus(ServerAccountStatusEnum.Starting, launchItem); launchResult = mgr.LaunchGameHandlingDelaysAndTitles(_worker); } finally { _gameSessionMap.EndLaunchingSession(launchItem.ServerName, launchItem.AccountName); } if (launchResult.Success) { ++serverIndex; // Let's just wait for game monitor to check if the character list changed // b/c the AccountManager is subscribed for that event //CallUiNotifyAvailableCharactersChanged(); // Pick up any characters - experimental 2017-04-10 // CallUiLoadUserAccounts(); // Pick up any characters - before 2017-04-10 _gameSessionMap.StartSessionWatcher(session); workerReportProgress("Launched", launchItem, serverIndex, serverTotal); } else { globalQueue.Enqueue(launchItem); workerReportProgress("Requeued", launchItem, serverIndex, serverTotal); } if (_worker.CancellationPending) { e.Cancel = true; return; } } }
private void update_result_list_worker_DoWork(object sender, DoWorkEventArgs e) { WorkerArgs args = (WorkerArgs)e.Argument; update_result_list_view(update_result_list_worker, args.ValueType, true, 0, 1.0f); }
private void DoStart(object sender, RoutedEventArgs e) { if (!ReferenceEquals(bw, null) && bw.IsBusy) return; bw = new BackgroundWorker(); bw.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted; bw.WorkerReportsProgress = true; bw.WorkerSupportsCancellation = true; // prepare args WorkerArgs args = new WorkerArgs(); args.DatabasePath = App.Config.MPTVSeriesDatabasePath; args.Directory = mediaPath.Text; args.DeleteXmlAfterMkvUpdate = (bool) deleteXmlAfterUpdate.IsChecked; if (Equals(sender, writeXmlTagButton)) { if (!WriteXmlTagsInit()) return; bw.DoWork += WriteXmlTags; bw.ProgressChanged += WriteXmlTagsProgressChanged; bw.RunWorkerCompleted += (o, eventArgs) => { writeMkvButton.IsEnabled = true; }; } else if (Equals(sender, writeMkvButton)) { if (!WriteMkvTagsInit()) return; bw.DoWork += WriteMkvTags; bw.ProgressChanged += WriteMkvTagsProgressChanged; } contentDock.IsEnabled = false; progressText.Text = string.Empty; progressBar.Style = FindResource("greenProgress") as Style; progressDock.IsEnabled = true; progressDock.Visibility = Visibility.Visible; bw.RunWorkerAsync(args); }