0

I created an Webform application which allow user to upload file which using AJAX and FileHandle.ashx in Asp.Net I'm trying to make it run asynchronous but it doesn't work as well. The code below return "StartSavedEnd" which mean await doesn't work since my file take 10second to upload. Any advice? Many thanks

    public override async Task ProcessRequestAsync(HttpContext context)
    {
    context.Response.ContentType = "text/plain";
    context.Response.Write("Start");

    await SaveFile(context);

    context.Response.Write("End");
    }
async Task SaveFile(HttpContext context)
{
    var task = Task.Run(() =>
    {
        if (context.Request.Files.Count > 0)
        {
            HttpFileCollection files = context.Request.Files;
            foreach (string key in files)
            {
                HttpPostedFile file = files[key];
                string fileName = file.FileName;
                fileName = context.Server.MapPath(fileName);
                file.SaveAs(@"C:\TestZip.zip");
                context.Response.Write("Saved");

            }
        }
    });
    await task;
}
5
  • Does this answer your question? ASP.NET Webforms with async/await Commented Jun 23, 2021 at 7:05
  • @GSerg I've take a look at that thread but ConfigureAwait(false) doesn't work for me. No answer has been accepted as answer btw Commented Jun 23, 2021 at 7:20
  • Try replacing await SaveFile(context) by SaveFile(context).GetAwaiter().GetResult(). GetAwaiter/GetResult don't create a deadlock in legacy ASP.net. (unlike ASP.net Core) Commented Jun 23, 2021 at 7:36
  • @GuyatMercator It showing compile error "cannot wait for void" when i added .GetAwaiter().GetResult() Commented Jun 23, 2021 at 7:43
  • Why don't you run this code simply synchronously? TaskRun will create another thread but you want to wait for the end of its execution. So sync execution seems to suit. Background tasks in webforms are not trivial. Have a look at this : haacked.com/archive/2011/10/16/… Commented Jun 23, 2021 at 14:54

1 Answer 1

0

I'm trying to make it run asynchronous but it doesn't work as well. The code below return "StartSavedEnd" which mean await doesn't work since my file take 10second to upload.

await doesn't make file uploads run faster, and await doesn't return early from HTTP requests.

In order to make your system seem more responsive, you'll need to do the upload in the background on the client side, e.g., using a technology like AJAX.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.