提问者:小点点

使用Task.run()时如何避免OutOfMemoryException?[副本]


当我在启动时调用此方法时,我得到OutOfMemoryException。StartSignalR方法应该运行一个每秒调用Update()方法的任务。

  public void StartSignalR()

    {

        Task t = Task.Run(() =>
        {
            try
            {
                bool push = true;
                while (push)
                {
                    Update();
                }
            }
            catch (System.Exception ex)
            {
                LogManager.LogError(ex);
            }
        });
    }

我在Update()中使用task.delay

 private async static void Update()
    {
        await Task.Delay(1000);
        
        Updater.MPrice();
    }

共1个答案

匿名用户

要使真正等待,必须将lambda声明为,并将声明为方法。

public void StartSignalR()
{
    //added async
    Task t = Task.Run(async () =>
    {
        try
        {
            bool push = true;
            while (push)
            {
                //await the Update method
                await Update();
            }
        }
        catch (System.Exception ex)
        {
            LogManager.LogError(ex);
        }
    });
}

通过此更改,方法必须返回一个

//changed signature
private async static Task Update()

这很可能会减少内存占用,因为当前您正在疯狂地触发方法。