我有这个示例代码,它使用 begininvoke 异步调用一个方法,我在 webform 上的按钮单击事件上执行它。
单击按钮后,用户将被重定向到另一个页面,用户在此等待结果。
AuthorizePayment 方法需要很长时间才能运行并返回一个 int 代码。我想将该 int 值存储在会话或 cookie 中的某处(但不显示)当我访问 Session 以添加该代码时,它会引发空异常。如何将此结果保存在会话或 cookie 中?
任何想法?
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.
}
}