垃圾收集器是否会在 .NET 中的异步调用期间销毁临时未引用的对象?

Does the Garbage Collector destroy temporarily unreferenced objects during async calls in .NET?(垃圾收集器是否会在 .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 中的异步调用期间销毁临时未引用的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)