我正在将文件读入内存,然后尝试为每一行进行webservice调用。我想要做的是: 1.读入文件 2.创建新主题 - >执行第1行的Web服务调用 3.创建新主题 - >执行第2行的Web服务调用 4.使用服务调用1或2的结果更新“状态”框,该服务调用首先返回
所以换句话说,我正在尝试为文件中的每一行做多个Web服务调用,并在它们返回时更新状态框。我不想拨打一个电话,然后在第一个电话回来后开始第二个电话。
编辑:忘记提及调试时,我注意到只进行了一次调用,因为readFileBackgroundWorker.IsBusy
在经过foreach循环时是true
,但是如果我删除了那么我得到一个错误This BackgroundWorker is currently busy and cannot run multiple tasks concurrently.
阅读文件:
private void uxReadFileButton_Click(object sender, EventArgs e)
{
uxFileStatusLabel.Text = String.Empty;
this.uxReadFileButton.Enabled = false;
this.uxCancelReadingFileButton.Enabled = true;
var clientList = ReadFile(uxFileNameBox.Text);
foreach (var client in clientList)
{
if (readFileBackgroundWorker.IsBusy != true)
{
readFileBackgroundWorker.RunWorkerAsync(client);
}
}
}
private void readFileBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var worker = (BackgroundWorker)sender;
ProcessClient((ClientObject)e.Argument, worker, e);
}
private void ProcessClient(ClientObject client, BackgroundWorker worker, DoWorkEventArgs e)
{
try
{
client.FileClientDischarge(SystemCode, UserName, Password);
int percent = (int)(Math.Ceiling(((double)(client.RecordNumber + 1) / 121) * 100));
worker.ReportProgress(percent, client);
}
catch (Exception ex)
{
worker.CancelAsync();
}
e.Result = client.RecordNumber;
}
答案 0 :(得分:1)
您的后台工作人员只运行一次的原因是,当您第二次拨打RunWorkerAsync()
时,它很忙。您应该为循环的每次迭代创建一个后台工作程序。
private void uxReadFileButton_Click(object sender, EventArgs e)
{
uxFileStatusLabel.Text = String.Empty;
this.uxReadFileButton.Enabled = false;
this.uxCancelReadingFileButton.Enabled = true;
var clientList = ReadFile(uxFileNameBox.Text);
BackGroundWorker bgw;
foreach (var client in clientList)
{
bgw = new BackgroundWorker();
bgw.DoWork += readFileBackgroundWorker_DoWork;
//bgw.RunWorkerCompleted +=
bgw.RunWorkerAsync(client);
}
}
private void readFileBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var worker = (BackgroundWorker)sender;
ProcessClient((ClientObject)e.Argument, worker, e);
}
private void ProcessClient(ClientObject client, BackgroundWorker worker, DoWorkEventArgs e)
{
try
{
client.FileClientDischarge(SystemCode, UserName, Password);
int percent = (int)(Math.Ceiling(((double)(client.RecordNumber + 1) / 121) * 100));
worker.ReportProgress(percent, client);
}
catch (Exception ex)
{
worker.CancelAsync();
}
e.Result = client.RecordNumber;
}
上查看此SO问题
答案 1 :(得分:0)
您应该尝试使用多线程,因为foreach循环在您的工作人员完成工作之前完成。
答案 2 :(得分:0)
您可以使用
之类的内容启动多个后台工作程序并行执行Web服务调用foreach (var client in clientList)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync(i);
}