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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T16:56:21+00:00 2026-05-31T16:56:21+00:00

Is it safe to left task unreferenced if i know for sure that it

  • 0

Is it safe to left task unreferenced if i know for sure that it doesn’t throw an exception? Will GC wait untill a task completes before collects it?

Here is an example of my method that converts an array of the tasks into one task that completes (is canceled or failed) when all tasks completes. My application fails with task unobserved exception (by logging Task.Id at any place where I use tasks I found that the task that left unobserved is the one supplied to this method or at least has the same id). I have no idea why this happens except the garbage collector collects the task returned from Task.Factory.ContinueWhenAll not waiting when it is completed as such it may also collect all my tasks from the array left unreferenced and if there are at least one failed task it will lead task unobserved exception. Sounds crazy but i don’t see another explanation to what heppens. So is it possible?

        public static Task ToWhenAllTask(this Task[] tasks, bool cancelIfAnyCanceled = true)
    {
        if (tasks != null && tasks.Length == 0)
            throw new ArgumentException();

        var tcs = new TaskCompletionSource<object>();

        Task.Factory.ContinueWhenAll(tasks, ts => {
            try
            {
                List<Exception> errors = null;
                bool canceled = false;

                foreach (Task task in ts)
                {
                    AggregateException ex = task.Exception;

                    if (ex != null)
                    {
                        if (errors == null)
                            errors = new List<Exception>();

                        errors.Add(ex.Flatten());
                    }

                    if (task.IsCanceled)
                        canceled = true;
                }

                if (errors != null)
                    tcs.TrySetException(errors);
                else if (cancelIfAnyCanceled && canceled)
                    tcs.TrySetCanceled();
                else
                    tcs.TrySetResult(null);
            }
            catch(Exception ex)
            {

                // there is nothing to fail in this method but just in case
                tcs.TrySetException(ex);
            }

        }, TaskContinuationOptions.ExecuteSynchronously);

        return tcs.Task;
    }

PS. To be honest I thought that until task is completed TaskScheduller holds a reference to it (and in my case the continuation task also holds a reference to the tasks array). So GC can’t collect the continuation task and all the tasks from array until all of them completes.

  • 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-31T16:56:23+00:00Added an answer on May 31, 2026 at 4:56 pm

    Finally I’ve found the reason for my problem. And the direct answer to my question posted at first lines is – yes, it is safe to left task unreferenced if you know for sure it won’t fail with error. And yes, tasks will not be collected by GC untill they complete BUT only if they started (i.e. they were scheduled on TaskScheduler)

    Word ‘BUT’ in capital letters above means that there can be a problem for very particular case: if you left an instance of Task in uscheduled state and loose all references to it.

    Here is concrete example (actually what happened with me when I posted the question here) if you do ContinueWhenAll on a few tasks, one of which failed with a error and at least one is not scheduled (and the remaining ones are completed if there are any) and you loose references to all of that tasks and also don’t save a reference to the one returned by ContinueWhenAll then all of them will be collected by GC next time it collects garbage. And that failed task from the ones passed in ContinueWhenAll will lead Task Unobserved Exception.

    Not scheduled task above means it was created by either of the ways:

    1. Just new Task(…) was called (without further call of Start
      method)
    2. it was created by TaskCompleteionSource but not set to
      completion, failed state or canceled.

    Such behavior looks consistent from TPL point of view. Just because you should not supply tasks that will never be scheduled to ContinueWhenAll method and wait forever. So in fact if none of other tasks passed in ContinueWhenAll were failed the continuation will just never happen rather than Task Unobserved Exception occured. That’s it!

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

Sidebar

Related Questions

Is it safe to assume that two itterations over the same collection will return
We know that the dateformat classes are not thread safe. I have a multi-threaded
Is it safe to assume that all implementations of org.springframework.context.MessageSource interface are thread-safe after
Is it safe to assume that event subscribers are called in order of subscription?
A question yesterday about doubled-checked locking started a chain of thoughts that left me
Possible Duplicate: How do you handle resources in MATLAB in an exception safe manner?
Is it safe to say that there is no such thing as a right
Is it safe to say that there is no such thing as a right
How safe is it to use Silverlight in production for a graphic form? Is
If I safe an Array and reload it, is there a possibility to get

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.