Nathan Kamenar
Nathan Kamenar

Reputation: 884

Running long synchronous operation asynchronously

Below I have a simple async example that is working as I would expect with the following output:

Starting
Processing Diff
Log Diff Initiated
Diff processed

I need to adapt this so that GetDiff is a synchronous operation that gets called asynchronously by LogDiff.

My basic scenario is as follows: When a user clicks a button to save a project I have to generate a diff between the new version of the project and the old version, and this is an expensive operation. I don't want the user to have to wait for this diff to complete because all they are really interested in is that their project is saved, so I would like this synchronous operation to be performed asynchronously in the background so users don't have to wait for it or even know about it.

This means that I don't even need a callback, I just want to fire off the code generating this diff in the background. With all of that in mind, how should I adjust my example to accomplish this?

Also just FYI I am on .net 4.0, which is why I have the Delay polyfill method in my example.

class Program
{

    static void  Main()
    {
        Console.WriteLine("Starting");
        LogDiff();
        Console.WriteLine("Log Diff Initiated");
        Console.ReadLine();
    }

    public static async Task LogDiff()
    {
        var results = await GetDiff("Processing Diff");
        Console.WriteLine(results);
    }

    public static async Task<string> GetDiff(string str)
    {
        Console.WriteLine(str);
        await Delay(2000);
        return "Diff processed";
    }

    public static Task Delay(double milliseconds)
    {
        var tcs = new TaskCompletionSource<bool>();
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Elapsed += (obj, args) =>
        {
            tcs.TrySetResult(true);
        };
        timer.Interval = milliseconds;
        timer.AutoReset = false;
        timer.Start();
        return tcs.Task;
    }
}

Upvotes: 0

Views: 81

Answers (1)

Antoine V
Antoine V

Reputation: 7204

Why don't you execute your heavy LogDiff() method in the separating Task?

    static void  Main()
    {
        Console.WriteLine("Starting");
        //Save project
        Console.WriteLine("Project saved");
        Task task = new Task(new Action(LogDiff));
        task.Start();
        Console.ReadLine();
    }

    public void LogDiff()
    {
        var results = GetDiff("Processing Diff");
        Console.WriteLine(results);
    }

Upvotes: 1

Related Questions