Home All Groups Group Topic Archive Search About

System.ComponentModel.BackgroundWorker runs DoWork handler twice

Author
19 Sep 2006 3:47 PM
Ian
Hi,

Using Visual c# 2005 express, I have a Form which utilises a button
click to start a BackgroundWorker thread. The thread calls a Soap proxy
class, derived by web reference, to consume a web service on a server.
Each time it runs, it runs the DoWork event handler code twice!  I've
tried adding a second event handler in to the DoWork event.  That one
only ran once whilst the Soap service consumer one still ran twice.

The code snippet below is the actual code for the button click, and
event handler codes, with the following notes:
- all the methods below are part of the Form class
- SoapClass represents the web reference derived class.
- the actual winform is a simple form with a username text field,
password text field and connect button.  it's very simple so I thought
it a waste of space to post all the form supporting code.

Any clues as to why this would happen?

Cheers

Ian

<code>

private void InitializeBackgoundWorker()
{
     this.backgroundTask.DoWork +=
         new DoWorkEventHandler(backgroundTask_DoWork);
     this.backgroundTask.RunWorkerCompleted +=
         new RunWorkerCompletedEventHandler(
     this.backgroundTask_RunWorkerCompleted);
}

private void backgroundTask_DoWork(object sender, DoWorkEventArgs e)
{
     SoapClass.apiResponse objFinalResponse ;
     SoapClass.clientAuth objClientAuth = new SoapClass.clientAuth();
     SoapClass.apiAuth objApiAuth = e.Argument as SoapClass.apiAuth;
     SoapClass.apiService objApiService = new SoapClass.apiService();
     objFinalResponse = objApiService.Authenticate(objClientAuth,
objApiAuth);
     e.Result = objFinalResponse;
}

private void backgroundTask_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
     if (e.Error != null)
     {
         MessageBox.Show("Failed!");
     }
     else if (e.Cancelled)
     {
         MessageBox.Show("Cancelled!");
     }
     else
     {
         SoapClass.apiResponse objFinalResponse = e.Result as
SoapClass.apiResponse;
         MessageBox.Show(objFinalResponse.code);

     }
}

private void connectButton_Click(object sender, EventArgs e)
{
     SoapClass.apiAuth objApiAuth = new SoapClass.apiAuth();
     objApiAuth.username = this.username.Text;
     objApiAuth.password = this.password.Text;
     this.backgroundTask.RunWorkerAsync(objApiAuth);
}

</code>

AddThis Social Bookmark Button