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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T13:19:21+00:00 2026-06-02T13:19:21+00:00

NOTE: I’m not saying this is a good idea, just trying to find out

  • 0

NOTE: I’m not saying this is a good idea, just trying to find out if there’s a ‘better’ option than this brute-force one.

This came up in a previous SO thread @ How to get the current task reference?

However, that thread was a bit more constrained by a particular interface.

The brute-force approach I threw together quickly just uses a dictionary of weak references.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GetCurrentTaskExample
{
    public static class TaskContext
    {
        // don't need a ConcurrentDictionary since we won't be reading/writing the same task id with different tasks concurrently
        private static readonly Dictionary<int, WeakReference> s_indexedTaskReferences = new Dictionary<int, WeakReference>();

        public static void AddAndStartTasks(IEnumerable<Task> tasks)
        {
            foreach (var task in tasks)
            {
                AddTask(task);
                task.Start();
            }
        }

        public static void AddTask(Task task)
        {
            s_indexedTaskReferences[task.Id] = new WeakReference(task);
        }

        public static Task GetCurrentTask()
        {
            var taskId = Task.CurrentId;
            if (taskId == null) return null;

            WeakReference weakReference;
            if (s_indexedTaskReferences.TryGetValue(taskId.Value, out weakReference) == false) return null;
            if (weakReference == null) return null; // should not happen since we don't store null as a value

            var task = weakReference.Target as Task;
            return task;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var tasks = Enumerable.Range(0, 100)
                .Select(i => new Task(VerifyCurrentTaskWorks, i))
                .ToArray();

            TaskContext.AddAndStartTasks(tasks);

            Task.WaitAll(tasks);
        }

        static void VerifyCurrentTaskWorks(object instanceIdentifier)
        {
            var currentTask = TaskContext.GetCurrentTask();

            if (currentTask.Id == Task.CurrentId)
            {
                Console.WriteLine("Verified for instance {0} that Task.CurrentId value of {1} matches Id property {2} of task {3}",
                                  instanceIdentifier, Task.CurrentId, currentTask.Id, currentTask);
            }
            else
            {
                var errorMessage = String.Format("TaskContext.GetCurrentTask() failed for instance {0} with Task.CurrentId value of {1} and currentTask.Id value of {2}",
                                  instanceIdentifier, Task.CurrentId, currentTask.Id);
                throw new InvalidOperationException(errorMessage);
            }
        }
    }
}

However, this clearly means whatever is creating the tasks is forced to deal with this additional headache, so it’s not very usable, especially WRT C#5 async methods where the task isn’t so explicitly created.

Again, probably a bad idea to have code that needs this, so consider it more akin to a thought exercise. 🙂

  • 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-02T13:19:23+00:00Added an answer on June 2, 2026 at 1:19 pm

    There’s not much of a better way, unfortunately, and since the eventual goal was to key off of Task.CurrentId, it’s indeed not even useful since we won’t have an ability to get ‘current task id’ for async methods (after the first await, so it’s returned to the caller already).

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

Sidebar

Related Questions

Note: I am not sure if this is better here, or at superuser, but
Note: I've read this and its not quite what I'm looking for: I have
Note the tag: VBA , not VB6, not VB.NET. This is specific to VBA
Note: this is NOT like this question I've been tasked to construct a survey
Note: NOT Javascript. :-) Hello, I just had a random thought, and have decided
Note: purely out of curiosity and not for any actual use case. I'm wondering
Note: This was posted when I was starting out C#. With 2014 knowledge, I
NOTE: I am not set on using VI, it is just the first thing
(Note: This is for MySQL's SQL, not SQL Server.) I have a database column
Note This is not a REBOL-specific question. You can answer it in any language.

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.