简体   繁体   中英

backgroundworker not firing RunWorkerCompleted event

i have a web application with a search form. The form is being used to search through my own database, but also at other databases through their API service. To provide a fast response, i have decided to split the work in main thread and the backgroundworker service.

Here is my method which runs the search task.

// search through other API
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.WorkerSupportsCancellation = true;
worker.WorkerReportsProgress = true;
worker.RunWorkerAsync(form);

// search in my api
...

// wait for API results
while (worker.IsBusy) {
    for (sbyte i = 0; i < sbyte.MaxValue; i++) ;
}
// handle data and show to user

And the methods are

private void worker_DoWork(object sender, DoWorkEventArgs e) {
    Forms f = e.Argument as Forms;
    if (f != null) {
        List<ApiResponse> result = GetDataFromOtherApi(f);
        e.Result = result;
    }
    else e.Result = null;
}

The GetDataFromOtherApi() method works fine in the single thread test. It also works when running the backgroundworker thread. I have set a breakpoint at the end and e.Result has values which i was looking for.

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
    List<ApiResponse> reply = e.Result as List<ApiResponse>;

    if (reply == null) ar = null;
    else if (reply.Any()) ar = reply;
    else ar = null;
}

the ar is a variable that the main thread can access to after the while loop has done with running. But, when placing a breakpoint at the start, it never stops there, the loop itself is continuous to the infinity ... It means that the event is never being fired.

Am i missing something ?

The BackgroundWorker progress & completed events are synchronised to run on the UI thread. I'd guess as you're blocking that thread, they'll never get fired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM