I have this sample code that calls a method asynchronously using begininvoke, I'm executing this on a button click event on a webform.
After the button click, the user is redirected to a different page, where the user waits for the result.
The AuthorizePayment method takes a long time to run and returns a int code. I want to store that int value somewhere in session or a cookie(but not to dispaly) When I access Session to add that code, it throws null exception. How do I save this result in a session or a cookie?
Any idea?
public class CreditCardAuthorizationManager
{
// Delegate, defines signature of method(s) you want to execute asynchronously
public delegate int AuthorizeDelegate(string creditcardNumber,
DateTime expiryDate,
double amount);
// Method to initiate the asynchronous operation
public void StartAuthorize()
{
AuthorizeDelegate ad = new AuthorizeDelegate(AuthorizePayment);
IAsyncResult ar = ad.BeginInvoke(creditcardNumber,
expiryDate,
amount,
new AsyncCallback(AuthorizationComplete),
null);
}
// Method to perform a time-consuming operation (this method executes
// asynchronously on a thread from the thread pool)
private int AuthorizePayment(string creditcardNumber,
DateTime expiryDate,
double amount)
{
int authorizationCode = 0;
// Open connection to Credit Card Authorization Service ...
// Authorize Credit Card (assigning the result to authorizationCode) ...
// Close connection to Credit Card Authorization Service ...
return authorizationCode;
}
// Method to handle completion of the asynchronous operation
public void AuthorizationComplete(IAsyncResult ar)
{
// See "Managing Asynchronous Completion with the EndInvoke Method"
// later in this chapter.
}
}
aspx
pages? How does the target page "wait" for the response, are you polling something from script? I agree with @usr generally that you should be using ajax instead of starting threads from an aspx codebehind (if that's what you're doing) but there's a lot of missing info here about the architecture to know what could be wrong. – ResnatronHttpContext
to your background thread and it's no longer available (e.g. null) when you later try to access it from that thread? Never tried that but makes sense. Use another mechanism to share this information between your background thread and the active session, e.g. try passing theCache
property of the currentHttpContext
- the cache is global and not bound to a specific context so I would think a reference to that should not die with the context. If that doesn't work then go right to the database? – Resnatron