Search code examples
c#wpfuploadhttpwebrequestcancellation

How TO Cancel Upload in c# WPF app


i'm really stuck at this, i need to know ho to Cancel uploading Image in wpf. below is the code that i use to upload. request.Abort() is not work, the exception is shown, but the image is still uploaded.

    private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
    {
        request = WebRequest.Create(postUrl) as HttpWebRequest;

        if (request == null)
        {
            throw new NullReferenceException("request is not a http request");
        }

        request.Method = "POST";
        request.ContentType = contentType;
        request.UserAgent = userAgent;
        request.CookieContainer = new CookieContainer();
        request.ContentLength = formData.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(formData, 0, formData.Length);
            requestStream.Close();

        }
        GlobalManagement.isCancelingUpload = false;
        var response = request.GetResponse() as HttpWebResponse;
        request = null;
        return response;
    }

Solution

  • To abort the request you can probably try making the request in a separate thread and then aborting the thread when you want to cancel it. This will probably signal the server that the request was aborted and subsequently the request will be aborted.

    Or maybe you can kill it by specifying the Timeout property artificially to make it timeout. This will most likely abort it. Timeout Property

    Another alternative is to kill the process, I would argue launching it inside a new AppDomain and dropping the AppDomain when you want to kill the request; instead of aborting a thread inside your main process.

    You could also use the BeginGetResponse method and then use the abort method in the class of the request. I doubt that Abort would work with the snynchronous GetResponse.