1

I want to refactor some code that starts a new thread to use async await The code execute long running tasks in a queue. It was in Framework 4 and I am moving up to 4.5.2

Here is the old code

public void Spawn(object data)
{
   var pts = new ParameterizedThreadStart(DoWork);
   new Thread(pts).Start(data);
}
public void DoWork()
{
   // things to run in new thread
}

How do I make DoWork run in a new thread?

I have tried the following

public async Task DoWork()
{
   // things to run in new thread
}

However I can't figure out how to call it inside Spawn. If I try

await DoWork()

then intellisense wants me to make Spawn() Async so this is starting to look like a big refactor. Am I on the right path?

Kirsten
  • 15,730
  • 41
  • 179
  • 318
  • Are you trying to invoke this function in a new *process*, or a new *thread*? – James Jun 02 '18 at 00:18
  • Note: "Process" and "Thread" do not mean the same thing. Processes are completely separate instances of an application (you would see them in task manager). Threads are individual workers in the same application, running more or less independently of each other. Which are you trying to do? – dodexahedron Jun 02 '18 at 00:19
  • Oops, thanks, I fixed the question to say thread. – Kirsten Jun 02 '18 at 00:22
  • 1
    Why were you creating a new thread in the first place, instead of using the thread pool? Is this long running? Are you expecting a result back from `DoWork`? – Paulo Morgado Jun 02 '18 at 11:58
  • The task is long running it does not return a result although it does call back. Thanks for the question about why it is a new thread. I am studying `https://stackoverflow.com/questions/230003/thread-vs-threadpool?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa` to try and understand why this decision was made. – Kirsten Jun 03 '18 at 00:10

1 Answers1

1

The very simplest thing for you to do, if you just want to make something happen on a background thread, is to do the following:

Task.Run( () => DoWork() );

Then you do not need to make the DoWork function a Task or async. If you still want the ability to await it, then you can await the task returned by Task.Run, or else call the Wait() function on it (beware of deadlock potential, if you do that).

dodexahedron
  • 4,584
  • 1
  • 25
  • 37