使用异步任务方法时,需要在方法之前放置等待。我需要以非 UI 阻塞方式执行代码并且不想等待。我唯一的想法是使用:
private void TaskFactory()
{
CancellationTokenSource token_TaskFactory = new CancellationTokenSource();
ParallelOptions parOpts = new ParallelOptions();
parOpts.CancellationToken = token_TaskFactory.Token;
parOpts.MaxDegreeOfParallelism = Environment.ProcessorCount;
TaskCreationOptions atp = new TaskCreationOptions();
atp = TaskCreationOptions.PreferFairness;
Task TaskFactory = Task.Factory.StartNew(() =>
{
if (!token_TaskFactory.IsCancellationRequested)
{
Thread.Sleep(5000);
}
else
{
}
}, token_TaskFactory.Token, atp, TaskScheduler.Default);
}