Start code snippet in a new thread

The problem is that i want to write small code snippets exactly at a certain position in my code. This code snippets should be executed in a new thread and run in background. I am working with c# in Visual Studio. It is not needed to consider parallelism, that means that i don't need to do any locking of resources. Until now i have only found solutions to do this by creating a new method for each code snippet i need, and state them as static. This allows me to call for example: Thread thread = new Thread(DoSomething); thread.Start(); If "DoSomething" is my method containing the code i want to execute. I want to achieve the following: //1. Code until this position //2. Code to run in a new thread //3. Code that runs after thread is started Thanks for all your help!
1 answer

Passing delegate method as Parameter to start it as an own thread

To achieve the following sequence:

//1. Code until this position

//2. Code to run in a new thread

//3. Code that runs after thread is started

Just do the following:

Use the class ParameterizedThreadStart and pass the "code snippet" as an Action as parameter.
An example looks like this:

Create two methods:

public void RunMethodOnThread(Action action)
{
Thread thread1 = new Thread(new ParameterizedThreadStart(ExecuteInThread));
thread1.Start(action);
}

private void ExecuteInThread(Object a)
{
Action action = a as Action;
action.Invoke();
}

After that you can use the following call in your code, by passing a so called delegate function as an Parameter:

//1. Code until this position

RunMethodOnThread(delegate
{
//2. Code to run in a new thread
});

//3. Code that runs after thread is started

I know the solution seems a little bit complex, but by going this way you can achieve a very good reuse of your code and it is really easy to use it, especially if you have a lot of small "code snippets" that should run in a new thread.

Taggings: