垃圾收集器是否会在 .NET 中的异步调用期间销毁临时未引用的对象? [英] Does the Garbage Collector destroy temporarily unreferenced objects during async calls in .NET?

查看:17
本文介绍了垃圾收集器是否会在 .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 中的异步调用期间销毁临时未引用的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆