有没有垃圾收集过程中的.NET异步调用销毁暂时未引用的对象? [英] Does the Garbage Collector destroy temporarily unreferenced objects during async calls in .NET?

查看:119
本文介绍了有没有垃圾收集过程中的.NET异步调用销毁暂时未引用的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我将在.NET,即HttpWebRequest.BeginGetResponse一个异步调用,并HttpWebRequest对象不是在更广阔的范围内引用。将垃圾收集摧毁它,会出现问题?

例如code:

 使用系统;
使用System.Net;

公共类AsyncHttpWebRequest
{
    无效的主要()
    {
        变种请求= HttpWebRequest.Create(http://www.contoso.com);
        VAR的结果= Request.BeginGetResponse(GetResponseCallback,NULL);
    }

    私人无效GetResponseCallback(IAsyncResult的AsyncResult)
    {
        // 做一点事..
    }
}
 

替代版本(该请求被通过为AsyncState):

 使用系统;
使用System.Net;

公共类AsyncHttpWebRequest
{
    无效的主要()
    {
        变种请求= HttpWebRequest.Create(http://www.contoso.com);
        VAR的结果= Request.BeginGetResponse(GetResponseCallback,请求);
    }

    私人无效GetResponseCallback(IAsyncResult的AsyncResult)
    {
        // 做一点事..
    }
}
 

解决方案

一个对象被认为是活着的和非符合垃圾收集,如果任何活动线程包含对它的引用,或者如果它引用静态(直接或间接地在两个例)。

在这两个例子中的异步API有一个参考,你的要求(如异步IO操作提出线程池内),所以它不会被垃圾收集,直到它完成。

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..
    }
}

解决方案

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).

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天全站免登陆