Pregunta

Hi,

I have a simple ASP.NET MVC C# webpage that users can submit Title, Descirption, Tags and a link(URL). The post to the service is sent with JASON(AJAX) and works great for the most part. But sometimes the post just hangs and nothing happens when this happens it will also be vary slow to load any other page of this website.

The webmethod is real simple, first it stored the data to the database and then it uses HttpWebRequest to fetch the URL page. The fetched page is then read(header data) and in most cases it stores a image.

I suspect that the hangig is due to HttpWebRequest taking to long. The request method starts with this :

if (url != null && url.Length > 0)
                {
                    request = (HttpWebRequest)HttpWebRequest.Create(url);

                    dirInfo.Create();

                    request.UserAgent = ConfigurationManager.AppSettings["DomainName"];
                    webresponse = (HttpWebResponse)request.BeginGetResponse( .GetResponse();
                    if (webresponse.ContentType.StartsWith("image/"))
                    {
                        using (WebClient tmpClient = new WebClient())
                        {
                            client.DownloadFile(url, postThumbnailsTemp + "\\" + fileName);
                        }

                        if (SavePostImage(postThumbnailsTemp + "\\" + fileName, postId))
                            return true;
                    }


                    if (webresponse.ContentType.StartsWith("text/html") || webresponse.ContentType.StartsWith("application/xhtml"))
                    {
                          var resultStream = webresponse.GetResponseStream();
                          doc.Load(resultStream);

The question is if it might be better to use a async call here? Like the HttpWebRequest.BeginGetResponse? This would mean that the user might be redirected to the post page before the URL webpage is read and stored.

¿Fue útil?

Solución

If you are using web api for example, you can change your api controller action to be async. If you do so, the response will NOT return to the client until the task has completed but it will also not block other client/threads!

Example

[HttpPost]
public async Task<HttpResponseMessage> Post([FromBody]MyObject obj)

Within the method you should also use the async await pattern to create your custom request...

Have some articles for further information of how to build async web apis

http://blogs.msdn.com/b/webdev/archive/2013/09/18/scaffolding-asynchronous-mvc-and-web-api-controllers-for-entity-framework-6.aspx

http://www.dotnetcurry.com/showarticle.aspx?ID=948

and maybe watch this video

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top