Task.run在C#中创建内存不足异常 [英] Task.run creates out of memory exception in C#

查看:609
本文介绍了Task.run在C#中创建内存不足异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下逻辑:



if(testList.Count> = 512)

{

double [] testarry = testList.ToArray();

Task.Run(()=> SendMessage(testarry));

testList.Clear( );

}

每隔300毫秒我需要SendMessage,处理后发送消息需要接近400毫秒。所以我想到使用Task.Run,​​我相信每次调用都会创建一个新任务。但我的程序在运行几个小时后会出现内存异常。任何人都可以帮帮我吗?



我尝试了什么:



我想过使用一个任务,但由于我的处理需要更多的时间,我可能会错过一些点

I am working with the following logic:

if (testList.Count >= 512)
{
double[] testarry = testList.ToArray();
Task.Run(() => SendMessage(testarry));
testList.Clear();
}
I have to SendMessage every 300 milli-second and it takes close to 400 milliseconds to send message after processing. So I thought of using Task.Run which I believe creates a new task on every call. But my program gives out of memory exception after running for few hours. Can anyone help me out?

What I have tried:

I thought of using a single task but since my processing takes more time, I may miss out some points

推荐答案

如果要发送需要400毫秒,你每发送一次300毫秒,那么你开始有多少线程并不重要:你仍然会有完全相同的问题,只是稍微延迟,甚至稍微提前一点。想一想:一旦你的处理器耗尽了免费内核,你启动的线程将被暂停等待轮到他们运行(因为一个线程或任务需要一个免费核心才能运行)。



提升线程数可能会使问题变得更糟,而不是更好,因为每个线程都会给系统增加内存和处理开销。



防止问题的唯一方法是加快邮件发送速度,或降低发送速度。
If it takes 400ms to send, and you send it every 300ms, then it doesn't matter how many threads you start: you will still have exactly the same problem, just very slightly delayed, or even slightly sooner. Think about it: once your processor runs out of free cores, the threads you kick off will be suspended waiting for their turn to run (since a thread, or "task" needs a free core in order to run).

Boosting the number of threads will probably make the problem worse, not better, because each thread adds both a memory and a processing overhead to the system.

The only way to prevent the problem is to speed up the message sending, or slow down the send rate.


这篇关于Task.run在C#中创建内存不足异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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