2

I have a simple function as the following:

    static Task<A> Peirce<A, B>(Func<Func<A, Task<B>>, Task<A>> a)
    {
        var aa = new TaskCompletionSource<A>();
        var tt = new Task<A>(() => 
            a(b =>
            {
                aa.SetResult(b);
                return new TaskCompletionSource<B>().Task;
            }).Result
        );
        tt.Start();
        return Task.WhenAny(aa.Task, tt).Result;
    }

The idea is simple: for any implementation of a, it must return a Task<A> to me. For this purpose, it may or may not use the parameter (of type Func<A, Task<B>). If it do, our callback will be called and it sets the result of aa, and then aa.Task will complete. Otherwise, the result of a will not depend on its parameter, so we simply return its value. In any of the situation, either aa.Task or the result of a will complete, so it should never block unless a do not uses its parameter and blocks, or the task returned by a blocks.

The above code works, for example

    static void Main(string[] args)
    {
        Func<Func<int, Task<int>>, Task<int>> t = a =>
        {
            return Task.FromResult(a(20).Result + 10);
        };
        Console.WriteLine(Peirce(t).Result); // output 20
        t = a => Task.FromResult(10);
        Console.WriteLine(Peirce(t).Result); // output 10
    }

The problem here is, the two tasks aa.Task and tt must be cleaned up once the result of WhenAny has been determined, otherwise I am afraid there will be a leak of hanging tasks. I do not know how to do this, can any one suggest something? Or this is actually not a problem and C# will do it for me?

P.S. The name Peirce came from the famous "Peirce's Law"(((A->B)->A)->A) in propositional logic.

UPDATE: the point of matter is not "dispose" the tasks but rather stop them from running. I have tested, when I put the "main" logic in a 1000 loop it runs slowly (about 1 loop/second), and creates a lot of threads so it is a problem to solve.

3 Answers 3

4

A Task is a managed object. Unless you are introducing unmanaged resources, you shouldn't worry about a Task leaking resources. Let the GC clean it up and let the finalizer take care of the WaitHandle.

EDIT:

If you want to cancel tasks, consider using cooperative cancellation in the form of a CancellationTokenSource. You can pass this token to any tasks via the overload, and inside of each task, you may have some code as follows:

while (someCondition)
{
    if (cancelToken.IsCancellationRequested)
        break;
}

That way your tasks can gracefully clean up without throwing an exception. However you can propogate an OperationCancelledException if you call cancelToken.ThrowIfCancellationRequested(). So the idea in your case would be that whatever finishes first can issue the cancellation to the other tasks so that they aren't hung up doing work.

1
  • @EarthEngine: Updated my answer, hope that helps. Jun 7, 2012 at 21:33
1

Thanks to @Bryan Crosby's answer, I can now implement the function as the following:

    private class CanceledTaskCache<A>
    {
        public static Task<A> Instance;
    }

    private static Task<A> GetCanceledTask<A>()
    {
        if (CanceledTaskCache<A>.Instance == null)
        {
            var aa = new TaskCompletionSource<A>();
            aa.SetCanceled();
            CanceledTaskCache<A>.Instance = aa.Task;
        }
        return CanceledTaskCache<A>.Instance;
    }

    static Task<A> Peirce<A, B>(Func<Func<A, Task<B>>, Task<A>> a)
    {
        var aa = new TaskCompletionSource<A>();
        Func<A, Task<B>> cb = b =>
        {
            aa.SetResult(b);
            return GetCanceledTask<B>();
        };
        return Task.WhenAny(aa.Task, a(cb)).Unwrap();
    }

and it works pretty well:

    static void Main(string[] args)
    {
        for (int i = 0; i < 1000; ++i)
        {
            Func<Func<int, Task<String>>, Task<int>> t = 
                async a => (await a(20)).Length + 10;
            Console.WriteLine(Peirce(t).Result); // output 20
            t = async a => 10;
            Console.WriteLine(Peirce(t).Result); // output 10
        }
    }

Now it is fast and not consuming to much resources. It can be even faster (about 70 times in my machine) if you do not use the async/await keyword:

    static void Main(string[] args)
    {
        for (int i = 0; i < 10000; ++i)
        {
            Func<Func<int, Task<String>>, Task<int>> t =
                a => a(20).ContinueWith(ta => 
                    ta.IsCanceled ? GetCanceledTask<int>() : 
                    Task.FromResult(ta.Result.Length + 10)).Unwrap();
            Console.WriteLine(Peirce(t).Result); // output 20
            t = a => Task.FromResult(10);
            Console.WriteLine(Peirce(t).Result); // output 10
        }
    }

Here the matter is, even you can detected the return value of a(20), there is no way to cancel the async block rather than throwing an OperationCanceledException and it prevents WhenAny to be optimized.

UPDATE: optimised code and compared async/await and native Task API.

UPDATE: If I can write the following code it will be ideal:

static Task<A> Peirce<A, B>(Func<Func<A, Task<B>>, Task<A>> a)
{
    var aa = new TaskCompletionSource<A>();
    return await? a(async b => {
        aa.SetResult(b);
        await break;
    }) : await aa.Task;
}

Here, await? a : b has value a's result if a successes, has value b if a is cancelled (like a ? b : c, the value of a's result should have the same type of b). await break will cancel the current async block.

0

As Stephen Toub of MS Parallel Programming Team says: "No. Don't bother disposing of your tasks."

tldr: In most cases, disposing of a task does nothing, and when the task actually has allocated unmanaged resources, its finalizer will release them when the task object is collected.

1
  • In normal case, all task will complete normally or being canceled or there is thrown exceptions, and it is finally no longer running. I will not worry about disposing them in such a case. What I am concerning is, in my case, the task is still running even if the final result has been obtained. So I am actually looking for ways to stop them. Jun 7, 2012 at 5:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.