public void StartAutoExportTxt() { tokenSource = new CancellationTokenSource(); Console.WriteLine("StartAutoExportTxt"); IQueryable <GroundTruth> groundtruths = null; _ExportTask = Task.Factory.StartNew(() => { var GVContext = Startup.CreateDBContext(); while (true) { groundtruths = GVContext.GroundTruths.OrderBy(item => item.ip); foreach (GroundTruth groundtruth in groundtruths) { DeviceCache dv = GetDevice(groundtruth.ip); dv.ProcessOnce(); } Thread.Sleep(30000); if (tokenSource.IsCancellationRequested == true) { Console.WriteLine("Task {0} was cancelled before it got started.", tokenSource); tokenSource.Token.ThrowIfCancellationRequested(); } } }); }