I use Background Workers all the time, they are great for processing long time actions.
from your code
#region Background Work of My Request
private void ProcessMyRequest()
{
if (!bkgWorkerMyRequest.IsBusy)
{
lblMessageToUser.Text = "Processing Request...";
btnProcessRequest.Enabled = false;
bkgWorkerMyRequest.RunWorkerAsync();
}
}
private void bkgWorkerMyRequest_DoWork(object sender, DoWorkEventArgs e)
{
// let's process what we need in a diferrent thread than the UI thread
string r = GetStuffDone();
e.Result = r;
}
private void bkgWorkerMyRequest_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string myResult = (String)e.Result;
lblMessageToUser.Text = myResult;
btnProcessRequest.Enabled = true;
}
#endregion
private function string GetStuffDone()
{
NetBasisServicesSoapClient client = new NetBasisServicesSoapClient();
TransactionDetails[] transactions = new TransactionDetails[dataGridView1.Rows.Count - 1];
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
transactions[i] = new TransactionDetails();
transactions[i].TransactionDate = (string)dataGridView1.Rows[i].Cells[2].Value;
transactions[i].TransactionType = (string)dataGridView1.Rows[i].Cells[3].Value;
transactions[i].Shares = (string)dataGridView1.Rows[i].Cells[4].Value;
transactions[i].Pershare = (string)dataGridView1.Rows[i].Cells[5].Value;
transactions[i].TotalAmount = (string)dataGridView1.Rows[i].Cells[6].Value;
}
CostbasisResult result = client.Costbasis(dataGridView1.Rows[0].Cells[0].Value.ToString(), dataGridView1.Rows[0].Cells[1].Value.ToString(), transactions, false, "", "", "FIFO", true);
return ConvertStringArrayToString(result.Details);
}
all you need to do is call the method:
ProcessMyRequest();
and it will do the job. If you need to let the main Thread to be aware of progress, you can use the ProgressChanged
event
private void bkgWorkerMyRequest_ProgressChanged(
object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
in the bkgWorkerMyRequest_DoWork
method you need to change the code to have
//reports a percentage between 0 and 100
bkgWorkerMyRequest.ReportProgress(i * 10);
Remember:
You will, however get stuck when trying to Debug the method GetStuffDone
as it's that kinda hard debugging multi threaded applications
So, what I do is, debug everything without workers and then apply the workers.
Works fine for me, let me know if you need any more help on this.
added
I didn't aware that you were getting the Grid in the worker, sorry, for this, just send the grid as a argument and use it, please change:
bkgWorkerMyRequest.RunWorkerAsync(dataGridView1);
string r = GetStuffDone((GridView)e.Argument);
private function string GetStuffDone(GridView dataGridView1)