想象一下,我将在 .NET 中进行异步调用,即 HttpWebRequest.BeginGetResponse,并且 HttpWebRequest 对象没有在更广泛的范围内被引用。垃圾收集器会破坏它并引起问题吗?
示例代码:
using System;
using System.Net;
public class AsyncHttpWebRequest
{
void Main()
{
var Request = HttpWebRequest.Create("http://www.contoso.com");
var result = Request.BeginGetResponse(GetResponseCallback, null);
}
private void GetResponseCallback(IAsyncResult AsyncResult)
{
// Do Something..
}
}
替代版本(请求作为 AsyncState 传递):
using System;
using System.Net;
public class AsyncHttpWebRequest
{
void Main()
{
var Request = HttpWebRequest.Create("http://www.contoso.com");
var result = Request.BeginGetResponse(GetResponseCallback, Request);
}
private void GetResponseCallback(IAsyncResult AsyncResult)
{
// Do Something..
}
}