0

I am trying to upload many files Using c# file up-loader and enable the user to stop the process in the middle so I create backgroundworker to run upload on it but the cancellation button does not work (it fires after all the files is uploaded)and WorkerThread_ProgressChanged does not affect UI elements and the label text doesnot change and this is my code

protected void cancelupload_Click(object sender, EventArgs e)
{

    workerThread.CancelAsync();
    if (workerThread.CancellationPending)
    {
    }


}

private void WorkerThread_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    Uploadpercentage.Text= "Uploading... (" + e.ProgressPercentage + "%)";
}
private void WorkerThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        // lblStopWatch.Text = "Cancelled";
    }
    else
    {
        //  lblStopWatch.Text = "Stopped";
    }
}
private void WorkerThread_DoWork(object sender, DoWorkEventArgs e)
{
    DateTime startTime = DateTime.Now;
    _keepRunning = true;
    List<KeyValuePair<string, string>> Unuploaded_files = new List<KeyValuePair<string, string>>() { };
    int count = 0;
    while (_keepRunning && count < fileCollection.Count)
    {

        HttpPostedFile uploadfile = fileCollection[count];
        String fileName = Path.GetFileName(uploadfile.FileName);
        string fileExxtension = Path.GetExtension(uploadfile.FileName);
        if (ValidExtensions.Contains(fileExxtension))
        {
            if (File.Exists(Chosen_Site_Path + @"\" + Selected_folder_name.SelectedItem.Text + @"\" + fileName))
        {
            KeyValuePair<string, string> Unuploaded_file = new KeyValuePair<string, string>(fileName, "Another file exists with the same name!");
            Unuploaded_files.Add(Unuploaded_file);
        }
        else
        {
            uploadfile.SaveAs(Chosen_Site_Path + @"\" + Selected_folder_name.SelectedItem.Text + @"\" + fileName);
            log.INSERT_ACTIVITY_LOG(Session["User_PK"].ToString(), Session["User_Type"].ToString(), "Uploader Home Page : Uploaded " + fileName + "Selected site " + BASF_SITE_ID);
            log.INSERT_SITE_HISTORY(Session["User_PK"].ToString(), BASF_SITE_ID, "Uploaded file: " + fileName);
        }
    }
        else
        {
        KeyValuePair<string, string> Unuploaded_file = new KeyValuePair<string, string>(fileName, "File type is not allowed");
        Unuploaded_files.Add(Unuploaded_file);

    }
    count++;

        string timeElapsedInstring = (DateTime.Now - startTime).ToString(@"hh\:mm\:ss");

        int percent = (int)(((Decimal)count / fileCollection.Count ) *100);
        workerThread.ReportProgress(percent, timeElapsedInstring);

        if (workerThread.CancellationPending)
        {
            // this is important as it set the cancelled property of RunWorkerCompletedEventArgs to true
            e.Cancel = true;
            break;
        }
    }
    if (Unuploaded_files.Count == 0)
    {

        string message = "alert('Files Uploaded')";
        ScriptManager.RegisterClientScriptBlock(submitupload, this.GetType(), "alert", message, true);
    }
    else
    {
        string msg = "UNUPLOADED FILES:" + @"\" + "n";
        for (int i = 0; i < Unuploaded_files.Count; i++)
        {
            msg += Unuploaded_files[i].Key + ": " + Unuploaded_files[i].Value + @"\" + "n";
        }
        string alertmsg = "alert('" + msg + "')";
        ScriptManager.RegisterClientScriptBlock(submitupload, this.GetType(), "alert", alertmsg, true);
    }
    viewSites();
}
  • 2
    If the UI thread was blocked you woudn't be able to even click on a button. Your code contains *ASP.NET* specific calls like `ScriptManager.RegisterClientScriptBlock`. There's no main thread in an ASP.NET application and each request runs on a separate thread already. You don't need a BGW in this case – Panagiotis Kanavos Feb 13 '19 at 14:05
  • How about creating a boolean variable, assigning it to false initially and checking if it is true in your while loop. Of course you have to make it true when cancel button is clicked. – Ali Kanat Feb 13 '19 at 14:07
  • You are coding for web trying to use desktop paradigm, If you want to upload files asynchronously on a web application, check this https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously – Daniel Brughera Feb 13 '19 at 14:23
  • I don't see any reason to downvote the question, even it the OP efforts seems to be on a wrong direction, at least is doing an effort and asking properly – Daniel Brughera Feb 13 '19 at 14:29
  • the main problem is that the code inside cancelupload_Click doesnot execute until do_work function finish its work and WorkerThread_ProgressChanged function change the label-text after do_work function finish its work so they are not working on parallel so the do_work will never stop at the middle – Mariam Mira Feb 13 '19 at 20:34
  • @DanielBrughera would you please explain to me why this paradigm will not work with web – Mariam Mira Feb 13 '19 at 20:38
  • @PanagiotisKanavos already did it – Daniel Brughera Feb 13 '19 at 20:44

1 Answers1

-1

This situation is called a race condition and is a common concern in multithreaded programming. For more information about multithreading design issues, see Managed Threading Best Practices.