Search code examples
c#multithreadingtasktaskfactory

Task.Factory.StartNew depend on parent thread?


I'm running this thread inside a method from a WCF service library.

The code below is executed at the end of the method. I do this because i don't want the user to wait for a background process to complete that does not affect the output from the WCF to the client.

The problem that i have now is that if i execute that thread and the client gets the response, the parent thread is killed; killing this thread as well. How do i make it so that the parent thread waits for this thread to finish, while performing the rest of the operations?

         class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, string> sampleDict = getPopulatedDictionary();
        var result = run(sampleDict);
    }

    public static int run(Dictionary<string, string> sampleDict_)
    {

        PerformCalculations(sampleDict_);
        if (sampleDict_.Keys.Count > 10)
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                backgroundprocess(sampleDict_);
            });
        }
        //after returning i still want it to run
        return sampleDict_.Keys.Count;
    }

    private static void backgroundprocess(Dictionary<string,string> dict)
    {
        foreach (var k in dict.Keys)
        {
            dict[k] = new Random().Next(2666).ToString();
        }
    }
}

In short, i want this method to kick off that thread and move onto return the value X but still wait for that thread to finish AFTER it returns the value.


Solution

  • Couldn't you do it as a continuation of the parent task. So execute

    FameMappingEntry.SaveFameDBMap(toSaveIdentifiers); as a continuation of a successful completion of the parent task. And then you can wait on the continutation.

    var childTask = parentTask.ContinueWith((pt) =>
    {
       FameMappingEntry.SaveFameDBMap(toSaveIdentifiers);
    }, TaskContinuationOptions.OnlyOnRanToCompletion);
    

    And then you can decide if you want to wait on the child task or use another continuation.