문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

If you aren't going to do anything except wait for the background thread to complete, then you might as well just not create the new background thread in the first place and execute the code in-line.

Try this:

var task = System.Threading.Tasks.Task.Factory.StartNew(() =>
{
  lock (toSaveIdentifiers)
  {
      FameMappingEntry.SaveFameDBMap(toSaveIdentifiers);
  }
);

int x = dosomething();

task.Wait();
return x;

You should also lock objects in the thread that uses them, and not some other random thread.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top