Does the Garbage Collector destroy temporarily unreferenced objects during async calls in .NET?(垃圾收集器是否会在 .NET 中的异步调用期间销毁临时未引用的对象?)
问题描述
想象一下,我将在 .NET 中进行异步调用,即 HttpWebRequest.BeginGetResponse,并且 HttpWebRequest 对象没有在更广泛的范围内被引用.垃圾收集器会破坏它并引起问题吗?
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?
示例代码:
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 传递):
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..
}
}
推荐答案
如果任何活动线程包含对它的引用,或者如果它被静态引用(直接或间接在两者中例).
An object is considered alive and non-eligible for garbage collection if any live thread contains a reference to it, or if it's referenced statically (directly or indirectly in both cases).
在这两个示例中,异步 API 都会保留对您请求的引用(在提交异步 IO 操作的线程池中),因此在完成之前不会被垃圾收集.
In both examples the async API keeps a reference to your request (within the thread pool where async IO operations are lodged) and so it won't be garbage collected until it completes.
这篇关于垃圾收集器是否会在 .NET 中的异步调用期间销毁临时未引用的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:垃圾收集器是否会在 .NET 中的异步调用期间销毁临时未引用的对象?


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01