调用ReportProgress后,C#BackgroundWorker.ProgressChanged不会立即触发

时间:2018-03-15 14:48:21

标签: c# user-interface backgroundworker

代码如下所示:

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?

1 个答案:

答案 0 :(得分:0)

来自msdn

  

对ReportProgress方法的调用是异步的,并立即返回

它不会阻止for内的DoWork循环。

如果要同步报告进度,则可以自行使用同步Invoke方法(请参阅例如this)。在这种情况下,您甚至不需要BackgroundWorker,只需要另一个Thread