Imagine that I will make an async call in .NET, i.e. HttpWebRequest.BeginGetResponse, and the HttpWebRequest object isn't referenced at a broader scope. Will the Garbage Collector destroy it and cause problems?
Example code:
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..
}
}
Alternate version (with the request being passed as an 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..
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…