Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8078111
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T15:41:17+00:00 2026-06-05T15:41:17+00:00

I have a simple function as the following: static Task<A> Peirce<A, B>(Func<Func<A, Task<B>>, Task<A>>

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T15:41:18+00:00Added an answer on June 5, 2026 at 3:41 pm

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have got the following very simple code: function init() { var articleTabs =
I have the following function //simple function with parameters and variable function thirdfunction(a,b,c,d){ console.log(the
I have the following simple function: private void EnableDisable941ScheduleBButton() { if (this._uosDepositorFrequency.Value != null)
I have the following simple jquery snippet $(document).ready(function () { $.ajax({ url:myjson.json, dataType: 'json',
I have a very simple html page with the following javascript in it $(function()
Let's say I have the following, very simple block of code: <script> function hasVal(field)
I have the following function call: public static MvcHtmlString NavLinks( this HtmlHelper helper, IList<MenuItem>
I have a simple C# function: public static double Floor(double value, double step) {
I have a static library. This library have the following function defined int WriteData(LPTSTR
I have the following bit of code, simply: $(function() { $('a.add-photos-link').live('click', function(e) { $(this).colorbox({

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.