This one is actually something of a triviality, yet it can be very useful at times. Now a word of caution is due here, this object is built on System.Threading.Timer and should not be used to enqueue 12 million work items. Yet if you need to perform a simple task at some time in the future the “TimeoutAction” class can serve nicely. The follow example uses it to clean up a temp file after giving a spawned process time enough to open the file:

using CSharpTest.Net.Delegates;
using CSharpTest.Net.IO;

    public interface IDownloadedFile
    {
        string Extension { get; }
        void CopyTo(string filename);
    }
    public void SpawnDownload(IDownloadedFile file)
    {
        using (TempFile tmpFile = TempFile.FromExtension(file.Extension))
        {
            file.CopyTo(tmpFile.TempPath);
            System.Diagnostics.Process.Start(tmpFile.TempPath);
            //Schedule the file cleanup to happen after one minute.
            TimeoutAction.Start(TimeSpan.FromMinutes(1), TempFile.Delete, tmpFile.Detatch());
        }
    }

This beats the heck out of a work queue or writing a thread for simple and infrequent operations. One additional concern addressed, if the object is disposed or GC’d the event will fire giving you the opportunity to perform the task. In addition to example above, it is also possible to provide an Action to handle any errors, by default it writes to Diagnostics.Trace.

Comments