-1

I get OutOfMemoryException when I call this method on startup. StartSignalR method should run a Task which calls Update() method every second.

  public void StartSignalR()

    {

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

I use Task.Delay in Update()

 private async static void Update()
    {
        await Task.Delay(1000);
        
        Updater.MPrice();
    }
Guga Todua
  • 462
  • 2
  • 11
  • 27
  • `Task.Run` most certainly doesn't cause an OOM exception. You need to look at and debug your code, you have a memory leak somewhere – Camilo Terevinto Dec 28 '20 at 11:05
  • @CamiloTerevinto OOM doesn't happen if I don't call this method – Guga Todua Dec 28 '20 at 11:06
  • You're calling `Update()` probably millions of times per second, so whatever is inside `Updater.MPrice()` is leaking memory somewhere, or creating objects big enough to make your system run out of memory. You need to `await` the call to `Update` – Camilo Terevinto Dec 28 '20 at 11:09
  • Please share a [mcve] including the source code for `MPrice`. – mjwills Dec 28 '20 at 11:16
  • 1
    Also, you forgot to call `await` on `Update`, and `Update` should probably return `Task` not `void`. – mjwills Dec 28 '20 at 11:17
  • [Avoid async void](https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#avoid-async-void). – Theodor Zoulias Dec 28 '20 at 11:52

1 Answers1

2

To make your Task.Delay actually wait, you have to declare your lambda as async and await the Update method.

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);
        }
    });
}

With this change your Update method has to return a Task

//changed signature
private async static Task Update()

Chances are good that this should reduce the memory footprint, because currently you are firing the Update method like crazy.

Rand Random
  • 7,300
  • 10
  • 40
  • 88