Reputation: 267
I have a C# console application that needs to call a function immediately when the application begins running, in this example ExecuteForLoop();
.
This is how my C# console application starts running:
static void Main()
{
ExecuteForLoop();
Console.Write("Test");
}
the function ExecuteForLoop()
in this example does this:
ExecuteForLoop()
{
int example = 0;
for(;;)
{
example++;
}
}
The problem is that if I call the ExecuteForLoop()
function the Console.Write("Test");
function will not execute immediately. "Test"
will ONLY be outputted to my console once the for(;;)
loop within ExecuteForLoop()
stops looping.
How can I call ExecuteForLoop()
and continue executing code so the function Console.Write("Test");
will be outputted to my C# console application while the for(;;)
loop within the ExecuteForLoop()
function is still running?
Upvotes: 2
Views: 2704
Reputation: 14894
You should almost never use Thread
directly.
Use Tasks instead. They are a higher-level abstraction and are much easier to work with than threads.
A simple example:
var backgroundTask = Task.Run(() =>
{
Console.WriteLine("Background task started");
while (true)
{
//do something
}
});
Console.WriteLine("Back in main");
Console.ReadKey();
Another one, cancelling the task after a key is pressed and returning a result:
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
var backgroundTask = Task.Run(() =>
{
Console.WriteLine("Background task started");
long count = 0;
while (!token.IsCancellationRequested)
{
count++;
}
Console.WriteLine("Background task cancelled");
return count;
}, token);
Console.WriteLine("Back in main");
Console.ReadKey();
tokenSource.Cancel();
Console.WriteLine("Counter: {0}", backgroundTask.Result);
Console.ReadKey();
A great resource to learn more about tasks is Stephen Cleary's blog.
Upvotes: 4
Reputation: 6251
Use multi-threading:
static void Main()
{
var t = new Thread(() => ExecuteForLoop());
t.Start();
Console.Write("Test");
t.Join() // See this answer : http://stackoverflow.com/a/14131739/4546874
}
Also, that might not exactly be what you want. Are you sure you need an infinite for-loop in the method? If not, see the syntax for a for-loop
and set an exit condition accordingly.
"Test"
is not printed because in the previous line you call the ExecuteForLoop()
method, in which the program runs into an infinite loop. Since, both statements are in the same thread, the latter cannot be executed unless the previous is, which of course is impossible.
Upvotes: 1
Reputation: 16966
Create a Thread
and run your logic inside
static void Main()
{
Thread t = new Thread (ExecuteForLoop); // Kick off a new thread
t.Start();
Console.Write("Test");
t.Join(); // wait for thread to exit.
}
I recommend reading Albahari
articles/blog on threading, it is very detailed.
Upvotes: 2