我们正在开发一个Windows应用程序,它定期启动可能需要一些时间的操作.我们已经进入了一种模式,即在BackgroundWorker上运行这些操作,并为每个操作编写一个快速的WinForm,在这里您将表单传递给必要的参数,表单连接BackgroundWorker并进行函数调用,以及表单显示输出(进度条移动,文本填满更新等).
很明显,这种形式非常棒.表单副本之间唯一真正不同的部分是在哪个对象上调用哪个方法.所以我们喜欢做的是使它成为通用的,我们可以采用表单,传入一个对象(或静态调用的null?),一个函数名和一个参数数组,让它只是"去"从那里.我们已经能够用Reflection做到这一点.在这种情况下,我们不喜欢反思的是缺乏强烈的打字; 错误拼写方法调用之类的东西会在运行时捕获,而不是编译时.现在有什么可以使它更优雅和健壮吗?我听说有人谈论代表和表达树等事情; 但我不确定前者是否适用,对后者仍然有点暗淡.
我正在使用Google App Engine和Django 1.0开发一个网站(app-engine-patch)
我的程序的一个主要部分必须在后台运行并更改本地数据,并发布到远程URL
有人可以提出有效的方法吗?
我有以下代码用于从后台线程填充ListView(DoWork调用PopulateThread方法):
delegate void PopulateThreadCallBack(DoWorkEventArgs e);
private void PopulateThread(DoWorkEventArgs e)
{
if (this.InvokeRequired)
{
PopulateThreadCallBack d = new PopulateThreadCallBack(this.PopulateThread);
this.Invoke(d, new object[] { e });
}
else
{
// Ensure there is some data
if (this.DataCollection == null)
{
return;
}
this.Hide();
// Filter the collection based on the filters
List<ServiceCallEntity> resultCollection = this.ApplyFilter();
// Get the current Ids
List<Guid> previousIdList = this.GetUniqueIdList(listView);
List<Guid> usedIdList = new List<Guid>();
foreach (ServiceCallEntity record in resultCollection)
{
if (e.Cancel)
{
this.Show();
return;
}
else …Run Code Online (Sandbox Code Playgroud) 我有一个后台工作程序运行来复制一个巨大的文件(几GB),我想知道如何在副本中间取消该过程.我可以在复制之前检查CancellationPending属性,但在复制已经进行时不知道如何进行.
if (worker.CancellationPending) // check cancellation before copy
{
e.Cancel = true;
}
else
{
File.Copy("sourceFile", "destinationFile"); // need to cancel this
}
Run Code Online (Sandbox Code Playgroud)
请指教,谢谢!
我有一个C++/CLI应用程序,它有一个后台线程.我经常希望将结果发布到主GUI.我已经在其他地方读过,因为MethodInvoker可以为此工作,但我很难将语法从C#转换为C++:
void UpdateProcessorTemperatures(array<float>^ temperatures)
{
MethodInvoker^ action = delegate
{
const int numOfTemps = temperatures->Length;
if( numOfTemps > 0 ) { m_txtProcessor2Temperature->Text = temperatures[0]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
if( numOfTemps > 1 ) { m_txtProcessor2Temperature->Text = temperatures[1]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
if( numOfTemps > 2 ) { m_txtProcessor2Temperature->Text = temperatures[2]; } else { m_txtProcessor2Temperature->Text = "N/A"; }
if( numOfTemps > 3 ) { m_txtProcessor2Temperature->Text = temperatures[3]; } else { m_txtProcessor2Temperature->Text …Run Code Online (Sandbox Code Playgroud) 我正在使用它BackgroundWorker在后台做一些重要的事情,以便UI不会变得无法响应.
但今天我注意到,当我运行程序时,只使用了两个CPU中的一个.
有没有办法使用所有的 CPU BackgroundWorker?

这是我的简化代码,就好像你很好奇!
private System.ComponentModel.BackgroundWorker bwPatchApplier;
this.bwPatchApplier.WorkerReportsProgress = true;
this.bwPatchApplier.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bwPatchApplier_DoWork);
this.bwPatchApplier.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.bwPatchApplier_ProgressChanged);
this.bwPatchApplier.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bwPatchApplier_RunWorkerCompleted);
Run Code Online (Sandbox Code Playgroud)
private void bwPatchApplier_DoWork(object sender, DoWorkEventArgs e)
{
string pc1WorkflowName;
string pc2WorkflowName;
if (!GetWorkflowSettings(out pc1WorkflowName, out pc2WorkflowName)) return;
int progressPercentage = 0;
var weWorkspaces = (List<WEWorkspace>) e.Argument;
foreach (WEWorkspace weWorkspace in weWorkspaces)
{
using (var spSite = new SPSite(weWorkspace.SiteId))
{
foreach (SPWeb web in spSite.AllWebs)
{
using (SPWeb spWeb = spSite.OpenWeb(web.ID))
{
PrintHeader(spWeb.ID, …Run Code Online (Sandbox Code Playgroud) 我知道这不是关于取消BackGroundWorker的第一个问题,但我找不到解决问题的答案.
我有一个发送文件的方法..即时通讯使用backgroundworker来调用它..
所以如何在发送文件的中间取消backgroundworker ..我的意思是我应该放在哪里
if (backgroundWorker1.CancellationPending == true)
{
e.Cancel = true;
break;
}
Run Code Online (Sandbox Code Playgroud)
这是代码:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
List<object> job = (List<object>)e.Argument;
string srcPath = (string)job[0];
string destPath = (string)job[1];
SendFile(srcPath, destPath);
}
Run Code Online (Sandbox Code Playgroud)
发送方式:
private void SendFile(string srcPath, string destPath)
{
string dest = Path.Combine(destPath, Path.GetFileName(srcPath));
using (fs = new FileStream(srcPath, FileMode.Open, FileAccess.Read))
{
try
{
long fileSize = fs.Length;
if (sizeAll == 0)
sizeAll = fileSize;
sum = 0;
int count = 0;
data = …Run Code Online (Sandbox Code Playgroud) 我的Windows窗体应用程序中有一个后台工作程序.但是在_DoWork()完成之后程序没有响应并且我什么都做不了就太奇怪了.
这就是我正在做的事情.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
excelOperation(fileName);
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Open Excel File";
fDialog.Filter = "Excel Files|*.xls;*.xlsx";
fDialog.InitialDirectory = @"C:\";
if (fDialog.ShowDialog() == DialogResult.OK)
{
fileName = fDialog.FileName;
backgroundWorker1.RunWorkerAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
而excelOperation()是用excel文件操作的东西.
当我不使用_DoWork()时,我的意思是当我不使用BackgroundWorker时,没有问题.我不知道出了什么问题.
*编辑 - 整个代码:*
private void excelOperation(string sFile)
{
string str_merged = "";
if (sFile != "")
{
int rCnt = 0;
int cCount = 0;
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Makina …Run Code Online (Sandbox Code Playgroud) 我的GUI类中有一个后台工作程序.
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
ProgressClass obj = new ProgressClass();
Importer tradeImporter = e.Argument as Importer;
BackgroundWorker worker = sender as BackgroundWorker;
List<TradeUploadInfo> list = obj.AllocateTrades2(tradeImporter, false);
e.Result = list; //Passes the list for processing
}
Run Code Online (Sandbox Code Playgroud)
进口商是我自己的班级.现在,该AllocateTrades2方法已完成所有处理.
我的问题是,如何在不将bw作为参数传递的情况下在不同的类中执行方法bw.ProgressReport内部AllocateTrades2?
如果有人向我解释如何用事件做这件事,但是如果还有另一种优雅的方式,那会很棒.我很开心.
在下面的代码中,当BackgroundWorker启动时,SynchronizationContext 确实存在,但仍然,RunWorkerCompleted处理程序在不同的线程上执行RunWorkerAsync(),因此抛出异常.为什么?
当呼叫tempForm被删除时,它运行正常.(和同代以当MessageBox了Form那里.)
(代码显示a Form,启动一秒后BackgroundWorker引用另一个Form f1,然后显示第二个Form f1.)
public static Form1 f1;
static BackgroundWorker worker = new BackgroundWorker();
[STAThread]
static void Main()
{
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
f1 = new Form1();
using (Form1 tempForm = new Form1()) tempForm.ShowDialog();
//MessageBox.Show("A MessageBox won't cause the exception later. Only the Form does.");
if (SynchronizationContext.Current == null) throw new Exception("This is NOT thrown");
worker.RunWorkerAsync(); …Run Code Online (Sandbox Code Playgroud) backgroundworker ×10
c# ×7
.net ×4
winforms ×4
cancellation ×2
c++-cli ×1
delegates ×1
django ×1
events ×1
porting ×1
python ×1
reflection ×1