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 7650665
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T11:18:42+00:00 2026-05-31T11:18:42+00:00

I am working on an application in which getting data back to a serial

  • 0

I am working on an application in which getting data back to a serial process as fast as possible is important, but there can be multiple sources to get that data from. As well, sometimes one source is faster than the other, but you don’t know which source that will be. I am using ContinueWhenAny(…).Wait() to await the first Task to end in order to continue and return out of the calling method. However, I need to check the validity of the data first, and only then return (or if all Tasks have finished and none of them have valid data). Right now my code will return even invalid data if that’s the Task that finishes first.

Is there a way to do something like “ContinueWhenAny” but only when the Task.Result meets a certain condition, otherwise wait for the next task/etc.. until the last task finishes?

As well, I need to make sure after one result is valid, that the other threads Cancel out. This part is already working fine.

Currently, my code looks like this (stripped of exception handling, just the nuts and bolts):

        ResultObject result = null;
        var tokenSource = new CancellationTokenSource();
        var tasks = listOfSources
                .Select(i => Task.Factory.StartNew(
                    () =>
                        {
                            i.CancellationToken = tokenSource.Token;
                            //Database Call
                            return i.getData(inputparameters);
                        }, tokenSource.Token));

        Task.Factory.ContinueWhenAny(
                tasks.ToArray(),
                firstCompleted =>
                    {
                        //This is the "result" I need to validate before setting and canceling the other threads
                        result = firstCompleted.Result;
                        tokenSource.Cancel();
                    }).Wait();
        return result;

Any ideas? I don’t want to use ContinueWhenAll since if the first call takes 2 seconds and the second takes 10 seconds, I want to get back to the serial process in 2 seconds if the first call returns valid data, otherwise wait 10 seconds, hope that result has valid data, and only return invalid data if all Tasks have completed and return an invalid result.

——— UPDATE —-
Thanks zmbq for the great idea. The updated (working) code is below and fulfills all my requirements. One caveat however, the difference between this code and the previous code is that this code will return a null result if none of the Tasks produce a valid result, rather than the previous code which returns the invalid result itself. It wouldn’t be difficult to change this version to do so too, but I’m perfectly content returning a null in that case for my purposes.

        ResultObject result = null;
        var tokenSource = new CancellationTokenSource();
        var tasks = listOfSources
                .Select(i => Task.Factory.StartNew(
                    () =>
                        {
                            i.CancellationToken = tokenSource.Token;
                            //Database Call
                            return i.getData(inputparameters);
                        }, tokenSource.Token)).ToArray();

        result = GetFirstValidResult(tokenSource,tasks);

        return result;


   private ResultObject GetFirstValidResult(CancellationTokenSource tokenSource, Task<ResultObject>[] tasks)
    {
        ResultObject result = null;
        Task.Factory.ContinueWhenAny(
            tasks,
            firstCompleted =>
                {
                    var testResult = firstCompleted.Result;
                    if(testResult != null && testResult.IsValid())
                    {
                        result = testResult;
                        tokenSource.Cancel();
                    }
                    else
                    {
                        var remainingTasks = tasks.Except(new[]{firstCompleted}).ToArray();
                        if(remainingTasks.Any())
                        {
                            result = GetFirstValidResult(tokenSource, remainingTasks);
                        } 
                    }
                }).Wait();
        return result;
    }
  • 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-05-31T11:18:43+00:00Added an answer on May 31, 2026 at 11:18 am

    Well, if your firstCompleted callback would check the result, and call ContinueWhenAny on the remaining tasks in case the result is illegal, you’d be done.

    As always, I recommend you take a look at ZeroMQ. Fire the tasks and have each task write a message to an output queue if its result is legal. The main thread will block on the queue and return when there’s a valid message, or when all the tasks have finished already.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am working on an application which starts as a service but only if
I'm working on an application which stores data in tables, similar to an RDBMS.
I'm working on an application which has data imported from a foreign (and wholly
I am working on an application which works with GPS data. Part of the
I'm working on an application which accesses data from an Oracle 11g database. I'm
I'm working on a web application framework, which uses MSSQL for data storage, mostly
I am working on an application which reads in a huge amount of data
I am working on an application which draws a simple dot grid. I would
I am working on an application which sends an AJAX POST request (I'm using
I'm working on iphone application which needs to run offline at an exhibition. It

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.