为什么我的 Task.ContinueWith 不等待定义时间
Why my Task.ContinueWith not wait the define time
我正在使用此方法从我的主 UI 线程中使用并发线程打开特定工作:
private List<MyData> MyCollection;
private static CancellationTokenSource _tokenSource;
private void Start()
{
int concurrentThread = (int)nudConcurrentFiles.Value;
int loops = (int)nudLoops.Value;
var token = _tokenSource.Token;
Task.Factory.StartNew(() =>
{
try
{
while (Iteration.LoopFinished < loops)
{
Parallel.ForEach(PcapList.Files,
new ParallelOptions
{
MaxDegreeOfParallelism = concurrentThread //limit number of parallel threads
},
File=>
{
if (token.IsCancellationRequested)
return;
//do work...
});
Iteration.LoopFinished++;
Task.Delay(10000).ContinueWith(
t =>
{
}, _tokenSource.Token);
}
}
catch (Exception e)
{ }
}, _tokenSource.Token,
TaskCreationOptions.None,
TaskScheduler.Default).ContinueWith(
t =>
{
}
);
}
问题是在循环之后我想等待 10 秒而 Task.Delay(10000).ContinueWith
不等待这 10 秒而是立即开始另一个循环。
您需要调用Wait()
方法才能执行任务
Task.Delay(10000).ContinueWith(
t =>
{
}, _tokenSource.Token).Wait();
我正在使用此方法从我的主 UI 线程中使用并发线程打开特定工作:
private List<MyData> MyCollection;
private static CancellationTokenSource _tokenSource;
private void Start()
{
int concurrentThread = (int)nudConcurrentFiles.Value;
int loops = (int)nudLoops.Value;
var token = _tokenSource.Token;
Task.Factory.StartNew(() =>
{
try
{
while (Iteration.LoopFinished < loops)
{
Parallel.ForEach(PcapList.Files,
new ParallelOptions
{
MaxDegreeOfParallelism = concurrentThread //limit number of parallel threads
},
File=>
{
if (token.IsCancellationRequested)
return;
//do work...
});
Iteration.LoopFinished++;
Task.Delay(10000).ContinueWith(
t =>
{
}, _tokenSource.Token);
}
}
catch (Exception e)
{ }
}, _tokenSource.Token,
TaskCreationOptions.None,
TaskScheduler.Default).ContinueWith(
t =>
{
}
);
}
问题是在循环之后我想等待 10 秒而 Task.Delay(10000).ContinueWith
不等待这 10 秒而是立即开始另一个循环。
您需要调用Wait()
方法才能执行任务
Task.Delay(10000).ContinueWith(
t =>
{
}, _tokenSource.Token).Wait();