I had a requirement where i need to wait for a particular file to be available and the need to make operations on the file.
I thought of using Task to wait for this action to complete and throw an error if file is not available after certain amount of time. I made use of cancellation token service to make this happen. The following is the sample code for this.
using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace TaskWaitSample { public class Program { static void Main(string[] args) { var fileName = @"C:\TestFileDir\Narendra.txt"; CancellationTokenSource ts = new CancellationTokenSource(120000); var task = Task.Factory.StartNew(() => CheckForFile(fileName, ts.Token), ts.Token); if (task.Result) { Console.WriteLine("Got result"); } else { Console.WriteLine("Exiting after waiting"); } Console.WriteLine("Exited task"); Console.Read(); } public static bool CheckForFile(string fileName, CancellationToken ts) { while (!ts.IsCancellationRequested) { //Console.WriteLine("Checking at {0}", DateTime.Now.TimeOfDay); if (File.Exists(fileName)) { return true; } } return false; } } }