7

I seem to fail to create a foreground task. my main thread is supppose to call another thread and then exit. the other thread suppose to run forever

void MainThreadMain()
{
    task_main = Task.Factory.StartNew(() => OtherThread()) ;
    return;
}

void OtherThread()
{
  while(true)
  {
     TellChuckNorrisJoke();
  }
}

how can I ensure task_main will continue running even that Main Thread is dead? I assumed il do:

task_main.IsBackgorund = false; 

but no such option :\ I can make my main thread to wait a signal from my other thread that it passed to Foreground mode. but thats plain silly.

Nahum
  • 6,959
  • 12
  • 48
  • 69
  • 1
    You ensure this by *not* using a thread. Simply call OtherThread() directly, after renaming it of course. – Hans Passant Mar 14 '12 at 11:54
  • 2
    this post may help. http://stackoverflow.com/questions/6156878/can-threads-started-by-tasks-parallel-library-act-as-foreground-threads – Krishna Mar 14 '12 at 11:56

1 Answers1

7

The obvious question is: why don't you run your work on the main thread?

Assuming this is not an option, you should use a Thread not a Task. Then you can set:

Thread.IsBackground = false;

This will prevent your application from terminating while the worker thread is running.

Nick Butler
  • 24,045
  • 4
  • 49
  • 70
  • 1
    I am creating a service. as I understand it the service OnStart method suppose to call another thread and return. if theres no thread to keep program alive it will exit. – Nahum Mar 14 '12 at 12:02
  • 2
    Ah! A Windows Service is controlled by the [Service Control Manager](http://msdn.microsoft.com/en-us/library/windows/desktop/ms685150(v=vs.85).aspx). As such, it does not have a normal "Main Thread". `OnStart` is called by the SCM and you are correct in that it must return quickly. So yes, it makes sense to start a `Thread` ( not a `Task` ). You will also have to implement `OnPause` and `OnStop`. See [MSDN: Windows Service Applications](http://msdn.microsoft.com/en-us/library/y817hyb6.aspx). – Nick Butler Mar 14 '12 at 12:17