代码如下所示:
class Mainwindow: Window{
int progress = 0;
public void sendrequest(){
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += new ProgressChangedEventHandler (
worker_ProgressChanged);
worker.WorkerReportsProgress = true;
worker.RunWorkerAsync();
//...Here I sent requests to Bloomberg API
// Each request is handled by EventHandler
session.SendRequest(request, null);
}
public void EventHandler(Event eventObject, Session session){
progress ++;
Console.WriteLine (process);
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine("Doing work! calling progress report!");
(sender as BackgroundWorker).ReportProgress(progress, null);
Thread.Sleep(100);
}
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Started Change! " + e.ProgressPercentage);
pg1.Value = e.ProgressPercentage;
}
输出如下:
Doing work! calling progress report!
0
1
Doing work! calling progress report!
2
3
4
5
Doing work! calling progress report!
6
7
8
9
10
Doing work! calling progress report!
11
12
13
14
Doing work! calling progress report!
15
16
17
18
19
Doing work! calling progress report!
20
....
但我的worker_progressChanged在循环结束之前从未被调用过(int i = 0; i&lt; 100; i ++),因此我的进度条从未更新并保持为0.据我所知,ProgressChanged属于UI线程。调用ReportProgress后,我应该怎样做才能立即触发ProcessChanged?