cdub
cdub

Reputation: 25701

Learning about IAsyncResult requests and Threads in C#

I have the following lines of code in a submit button when a file gets uploaded. So the request starts and runs in the background and tells the user that the file is processing.

// Prepare the query string
string arguments = string.Format(
    "?guid={0}&sessionid={1}&seqstring={2}&torrstring={3}", 
    Server.HtmlEncode(_userGuid), Server.HtmlEncode(_guid), 
    Server.HtmlEncode(seqString.ToString()), 
    Server.HtmlEncode(TorRString.ToString()));

// Initialize web request
req = (HttpWebRequest)WebRequest.Create(
    string.Format("{0}{1}", pageUrl.ToString(), arguments));
req.Method = "GET";

// Start the asynchronous request.
IAsyncResult result = (IAsyncResult)req.BeginGetResponse(
    new AsyncCallback(RespCallback), null);

// this line impliments the timeout, if there is a timeout, the callback 
// fires and the request becomes aborted
// ThreadPool.RegisterWaitForSingleObject(
// result.AsyncWaitHandle, 
// new WaitOrTimerCallback(TimeoutCallback), 
// null, DefaultTimeout, true);

The user is given a code that responds to a file, but sometimes I think the thread dies and the database doesn't get updated so it appears that the file never finishes processing. How do I tell if the thread is still running? The user submits their code and if I do result.IsCompleted; it says that result is null.

Upvotes: 0

Views: 501

Answers (2)

Nick Butler
Nick Butler

Reputation: 24383

Could you edit your post and include the whole button click handler and the RespCallback and TimeoutCallback methods? That would make your question easier to answer. We need to know whether your page waits for the WebRequest to complete or not.

I'm guessing that your page does not wait, but your code works most of the time. If so, the WebRequest will run asynchronously with your normal page life-cycle. If the page completes before the WebRequest, IIS can recycle the app pool and your background request will be destroyed. It will work most of the time because IIS doesn't often choose to recycle and so the WebRequest will continue to completion.

Upvotes: 1

James Black
James Black

Reputation: 41858

You may want to look at this question, but I would question why you have a null at the end of BeginGetResponse instead of passing back RequestState. Also, are you certain that your database call isn't failing somewhere, and you are blaming the wrong part of your program?

Asynchronous upload using HttpWebRequest

Upvotes: 0

Related Questions