使用 Task.Run() 时如何避免 OutOfMemoryException?
How to avoid OutOfMemoryException when using Task.Run()?
启动时调用此方法时出现 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();
}
为了让您的 Task.Delay
真正等待,您必须将您的 lambda 声明为 async
和 await
Update
方法。
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);
}
});
}
通过此更改,您的 Update
方法必须 return Task
//changed signature
private async static Task Update()
这很有可能会减少内存占用,因为目前您正在疯狂地触发 Update
方法。
启动时调用此方法时出现 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();
}
为了让您的 Task.Delay
真正等待,您必须将您的 lambda 声明为 async
和 await
Update
方法。
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);
}
});
}
通过此更改,您的 Update
方法必须 return Task
//changed signature
private async static Task Update()
这很有可能会减少内存占用,因为目前您正在疯狂地触发 Update
方法。