【发布时间】:2011-09-19 13:49:42
【问题描述】:
我正在寻找在Thread/Task 中创建循环的正确方法/结构...
原因是,我需要每 15 秒检查一次数据库以获取报告请求。
这是我迄今为止尝试过的,但我得到了OutOfMemoryException:
private void ViewBase_Loaded(object sender, RoutedEventArgs e)
{
//On my main view loaded start thread to check report requests.
Task.Factory.StartNew(() => CreateAndStartReportRequestTask());
}
private void CreateAndStartReportRequestTask()
{
bool noRequest = false;
do
{
//Starting thread to Check Report Requests And Generate Reports
//Also need the ability to Wait/Sleep when there are noRequest.
reportRequestTask = Task.Factory.StartNew(() => noRequest = CheckReportRequestsAndGenerateReports());
if (noRequest)
{
//Sleep 15sec
reportRequestTask.Wait(15000);
reportRequestTask = null;
}
else
{
if (reportRequestTask.IsCompleted)
{
reportRequestTask = null;
}
else
{
//Don't want the loop to continue until the first request is done
//Reason for this is, losts of new threads being create in CheckReportRequestsAndGenerateReports()
//Looping until first request is done.
do
{
} while (!reportRequestTask.IsCompleted);
reportRequestTask = null;
}
}
} while (true);
}
private bool CheckReportRequestsAndGenerateReports()
{
var possibleReportRequest = //Some linq query to check for new requests
if (possibleReportRequest != null)
{
//Processing report here - lots of new threads/task in here as well
return false;
}
else
{
return true;
}
}
我做错了什么?
这是正确的方式还是我完全关闭了?
编辑:
最重要的是,我的 UI 必须仍然是响应式的!
【问题讨论】:
-
不是将循环放置在此任务中,而是在无限循环中创建任务。
-
您正在创建谁知道有多少任务。您的代码没有多大意义。您可能应该编辑和描述您想要完成的确切目标。
-
谁告诉你的进程何时结束?该程序?还是任务处理本身(即一旦你得到 FALSE 返回)?
-
值得注意的是,2021年的最佳实践是使用
Task.Run而不是Task.Factory.StartNew
标签: c# .net multithreading thread-safety multitasking