本文整理汇总了C#中System.ComponentModel.BackgroundWorker.ReportProgress方法的典型用法代码示例。如果您正苦于以下问题:C# BackgroundWorker.ReportProgress方法的具体用法?C# BackgroundWorker.ReportProgress怎么用?C# BackgroundWorker.ReportProgress使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.ComponentModel.BackgroundWorker
的用法示例。
在下文中一共展示了BackgroundWorker.ReportProgress方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddDirectoryAsync
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;
}
示例2: InstallApplication
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);
}
示例3: SavePeriodically
// 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;
}
}
示例4: doSpecificWork
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");
}
}
}
示例5: WorkerControl
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;
}
示例6: TakeFullSnapshot
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++;
}
}
示例7: CRTBaseMath
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();
}
示例8: AutoAllocate
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;
}
示例9: doSpecificWork
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");
}
}
}
示例10: ImportDataFromXml
/// <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;
}
示例11: Close
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");
}
示例12: addButton_Click
// 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();
}
}
示例13: descargaOpen
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);
}
示例14: CopyFile
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();
}
示例15: Run
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");
}