none
How to determine if specified thread waits current executing task? RRS feed

  • Question

  • There is a chance following call of Task.ThreadWaitsCurrentTask(someThread) returns true:

    Thread someThread = Thread.CurrentThread;
    Task task = Task.Run(() =>
    {
        if (Task.ThreadWaitsCurrentTask(someThread))
        {
            // ...
        }
    }); 
    task.Wait();
    If need something like Task.ThreadWaitsCurrentTask method.


    Wednesday, June 22, 2016 9:18 AM

Answers

  • Hi Igor,

    We can only get the thread state of one thread according ThreadState property.

    someThread.ThreadState

    >>"If need something like Task.ThreadWaitsCurrentTask method."

    You could implement this by following code.

    static Dictionary<int, int> waitPairs = new Dictionary<int, int>();
    static object syncObject = new object();
    
    static void Main(string[] args)
    {
        Thread someThread = Thread.CurrentThread;
        Task task = Task.Run(() =>
        {
            if (waitPairs.ContainsKey(Task.CurrentId.Value)&& waitPairs[Task.CurrentId.Value] == someThread.ManagedThreadId)
            {
    
            }
        });
    
        lock (syncObject)
        {
            waitPairs.Add(task.Id, someThread.ManagedThreadId);
            task.Wait();
        }
        
        Console.WriteLine("Finish");
    }
    Best Regards,
    Li Wang

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, June 23, 2016 4:48 AM
    Moderator