I am using a background worker for a time consuming operation ( To upload some data to server and download some data from server). All server communications are via http requests (GET,POST,PUT,Delete) and the code i used are
private void btnSync_Click(object sender, RoutedEventArgs e)
{
btnSync.IsEnabled = false;
BackgroundWorker syncWorker = new BackgroundWorker();
syncWorker.WorkerReportsProgress = true;
syncWorker.WorkerSupportsCancellation = true;
syncWorker.DoWork+=new DoWorkEventHandler(syncWorker_DoWork);
syncWorker.ProgressChanged+=new ProgressChangedEventHandler(syncWorker_ProgressChanged);
syncWorker.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(syncWorker_RunWorkerCompleted);
syncWorker.RunWorkerAsync();
}
private void syncWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker target = (BackgroundWorker)sender;
foreach (...........) // a loop to do some set of actions on some objects
{
target.ReportProgress(1, obj);
target.ReportProgress(2, obj);
target.ReportProgress(3, obj);
}
target.ReportProgress(4);
}
private void syncWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.ProgressPercentage == 1)
{
string id= e.UserState.ToString();
mySyncHelper.DOGETFROMServer(id); //Issue a GET request and read and process resposne (deserialize json data and insert to local DB)
}
if (e.ProgressPercentage == 2)
{
string id= e.UserState.ToString();
mySyncHelper.DOGETFROMServer(id);//Issue a GET request and read and process resposne(deserialize json data and insert to local DB)
}
if (e.ProgressPercentage == 3)
{
string id= e.UserState.ToString();
mySyncHelper.DOGETFROMServer(id);//Issue a GET request and read and process resposne (deserialize json data and insert/Update response data to local DB)
}
if (e.ProgressPercentage ==4)
{
mySyncHelper.DOPOSTToServer();//Issue a POST request and read and process resposne (deserialize json data and insert/Update response data to local DB)
mySyncHelper.DOPUTToServer();
mySyncHelper.DODELETEToServer();
}
}
private void syncWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
txtSyncStatus.Visibility = Visibility.Visible;
txtSyncStatus.Text = string.Concat(DbookLanguage.message_error, Environment.NewLine , e.Error.Message.ToString());
}
else
{
btnSync.IsEnabled = true;
txtSyncStatus.Text = "";
}
}
The problem i am facing is @ some stages the application is waiting some time for getting response back for the http requests and during this state the entire application goes to freezed state . The code i used for getting response from server is var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); and on this state the application is non responding .
How can i prevent this ? Is any other good way to make series of Http requests and make app UI interactive