Sebastian Araneda Sebastian Araneda - 1 year ago 61
C# Question

Run a piece of code while the main program is running

I was making a game on C# just for practice and learning (first program in C#) and I wondered if it was possible for C# to let me, while my program (the game) is running to simultaneously run another piece of code that would be the background music (just some Console.Beep() basic stuff).

In short, my question is if it would be possible for both the code for the background music and the one for the game to be in the same program, and if not, if there is an easy way to make it in just one console.

Answer Source

There are many options for threading. One of the most simpler are just using Task()

// Here I store the token for future use
processMe = new MyBackgroundProcess(ERPManager.CancellationTS.Token);

var aTask = new Task(() =>
{ // Everything here runs on another thread
}, ERPManager.CancellationTS.Token);

In this case, the "Run" method will run on a separte thread.

The "Token" is for cancelling the task. "processMe" stores the reference and asks "I am cancelled?"

For example, let's say Run() is like

public void Run()
  while (! token.IsCancellationRequested)

So you check if it's cancelled. When you finish, you just do a


On your main thread.

You can play with things like

List<Task> tasks = new List<Task> ();
tasks.Add(new Task(() => Process1.Run(), aCancellationToken));
tasks.Add(new Task(() => Process2.Run(), aCancellationToken));
tasks.Add(new Task(() => Process3.Run(), aCancellationToken));

And then do




And then query the status

if (tasks[0].IsCompleted()) { ... }
if (tasks[0].IsFaulted()) { ... }

You will face a lot of issues like concurrency and problems accessing UI elements, but this is a good start :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download