加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Func回调会导致内存泄漏吗?

发布时间:2020-12-15 20:54:16 所属栏目:百科 来源:网络整理
导读:每个人都知道从未为invocationList删除的事件处理程序可能会导致C#中的内存泄漏. 我的问题是,如果我们使用Func作为回调,我们可以有内存泄漏吗? (因此只支持一个用户) 以下面的示例(复制并粘贴到控制台应用程序中): class Program{ static void Main(string
每个人都知道从未为invocationList删除的事件处理程序可能会导致C#中的内存泄漏.
我的问题是,如果我们使用Func作为回调,我们可以有内存泄漏吗? (因此只支持一个用户)

以下面的示例(复制并粘贴到控制台应用程序中):

class Program
{
    static void Main(string[] args)
    {
        var m = new Manager();

        var c1 = new Channel();
        m.Add(c1);
        Console.WriteLine("m = {0}",GC.GetTotalMemory(true));

        Console.ReadLine();

        m.Remove(c1);
        Console.WriteLine("m = {0}",GC.GetTotalMemory(true));

        Console.ReadLine();
    }
}

public class Manager
{

    List<Channel> channels = new List<Channel>();

    public void Add(Channel c)
    {

        channels.Add(c);

        c.OnTick = OnTick;

        c.Start();
    }

    public void Remove(Channel c)
    {
        channels.Remove(c);
        //do we have a memory leak at this point?
        //does c1 still pointing to Manager func and cannot be GCed?
        c.Stop();
    }

    private Task OnTick(int i)
    {
        Console.WriteLine(i);
        return Task.FromResult(0);
    }
}

public class Channel
{
    public Func<int,Task> OnTick;
    Random r = new Random();
    private System.Timers.Timer aTimer;
    public Channel()
    {
        OnTick = i => Task.FromResult(r.Next());
    }

    public void Start()
    {
        aTimer = new System.Timers.Timer(1000);

        aTimer.Elapsed += (sender,args) => OnTick(r.Next());

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;
    }

    public void Stop()
    {
        aTimer.Dispose();
    }
}

解决方法

//do we have a memory leak at this point?

没有.在ANTS Memory Profiler上对此进行了测试以验证这一点.

//does c1 still pointing to Manager func and cannot be GCed?

Manager是订阅者,Channel是发布者.如果没有对Channel实例的引用,并且它符合条件的GC.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读