Code Mahek
  • Blog
  • About
  • Contact
  • Random Clicks
  • Resume
  • Ava Chat Bot

Fragrance
​of Programming

C#: Parent and Child Task Relationship

7/15/2017

Comments

 
Recently I had an interesting problem in my project. We frequently use task across all the code and it has really made our life easy as a developer but definitely there are some downside for it. Code becomes very messy sometime and its very difficult to debug the problem if there are any threading issue and race conditions are equally difficult.
So coming back to my problem, I had one function which was returning a Task and and I had a Task.WaitAll return from which the above function was called. So basically it looked as below:
Parent Child Task Relation

    
So from the above code you can see that after creating the parent task I am writing the continue block but I am returning the parent task. Now when code executes the Task.WaitAll, previously I thought that it will also wait for Continue task to complete. But to my surprise that's not that case, it will only wait for parent task to complete and will just move with the code and child task will complete later in separate thread. Now there are multiple ways to fix it.
  • Instead of returning the parent task in func1, we can return the whole parent task with continue block but we have to make sure we mention TaskCreationOptions.AttachedToParent in the continue block. In my case I was not able to do that because my function was not returning Task but Task<T> and when continue block was unable to do that. So I used the second option
  • Other way is, create a one task and include both Parent and child task in that and in my case I had to return the output of the Parent Task so I returned the Result of Parent task.
​It was quite tricky initially to fix the issue since I was not aware of parent-child task relationship. Anyways it was a good learning. Keep reading and do share if you liked it.
Comments
comments powered by Disqus

    RSS Feed

    Categories

    All
    Azure
    C#
    Cloud
    CodeProject
    CSharp
    DotNet Core
    Jetbrains
    .NET
    Rider
    Source Generators
    SQL
    Tech News
    Ubuntu
    Visual Studio 2015
    Visual Studio 2019
    Windows
    Windows 10

    Archives

    May 2020
    February 2019
    January 2019
    December 2018
    May 2018
    December 2017
    November 2017
    October 2017
    September 2017
    July 2017
    May 2017
    April 2017
    May 2015
    April 2015
    March 2015

    View my profile on LinkedIn

Location

Contact Us

    Subscribe Today!

Submit
  • Blog
  • About
  • Contact
  • Random Clicks
  • Resume
  • Ava Chat Bot