Task.Delay()循环是否会导致内存泄漏? [英] Does a loop with Task.Delay() create a memory leak?

查看:341
本文介绍了Task.Delay()循环是否会导致内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个异步缓冲区系统,在该系统中,我希望队列的一个使用者确保项目是按顺序处理的.使用者应定期检查队列,处理队列中的所有项目,然后休眠"一段时间. Task.Delay()对于这种系统似乎是完美的,因为与Thread.Sleep()不同,它在睡眠时不会消耗线程,并且与Timer不同,如果处理队列项所花费的时间超过睡眠间隔,它将不会启动新线程. .但是,我想知道如果任务系统跟踪原始任务的整个继续列表,则在while循环中使用Task.Delay()是否会造成内存泄漏.供参考,我的系统如下所示:

I am implementing an asynchronous buffer system where I want exactly one consumer of a queue to guarantee that items are processes in order. The consumer should check the queue periodically, process all items in it, and then "Sleep" for some interval. Task.Delay() seems perfect for such a system, since unlike Thread.Sleep() it won't consume a thread while sleeping and unlike Timer it won't launch a new thread if processing the queue items takes longer than the sleep interval. However, I'm wondering if using Task.Delay() in a while loop will create a memory leak if the task system is tracking the entire continuation list for the original task. For reference, my system looks like:

void EnqueueItem(Item item) {
    lock (this._lock) { this._items.Add(item); }
}

async Task Consumer() {
    while (true) {
        await Task.Delay(interval).ConfigureAwait(false);

        Item[] items = null;
        lock (this._lock) {
            if (this._disposed) { return; }
            if (this._items.Count > 0)
            {
                items = this._items.ToArray();
                this._items.Clear();
            }
        }
        if (items != null) { Process(items); }
    }
}

// in the constructor of the buffer
this.Consumer();

推荐答案

它不会导致内存泄漏,但是如果您处于紧密循环中,您可能会 想要处理任务而不是等待他们的定稿器

It won't cause a memory leak, however if you are in a tight loop you may want to dispose the tasks rather than waiting for their finalizer

例如

var t = Task.Delay(interval);
await t.ConfigureAwait(false);
t.Dispose();

但是您可能不想这样做,也不必这样做(请参阅

But you probably don't want to, and shouldn't need to (see Do I need to dispose of Tasks? )

这篇关于Task.Delay()循环是否会导致内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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