简体   繁体   中英

Completely new to code, is there a way I can make a loop constantly run whilst the rest of the code continues in a c# console application?

I do apologize if this is a bad question, literally started learning code days ago. I am looking for a way to make a loop run in the background whilst the rest of the code continues on. In ac# console application.

Look into threads. They allow your program to do two things at once, which sounds like your goal. Here is a tutorial: https://msdn.microsoft.com/en-us/library/aa645740%28v=vs.71%29.aspx

Just a note, generally threads aren't the easiest thing to learn right after you started coding. Maybe if you provide more details on what problem you are trying to solve, we can look for easier solutions too.

This is actually a surprisingly complex topic :)

There's two main approaches that you can use, based on what exactly you're trying to do. If you're doing CPU work, the only real option you have is using multi-threading:

var someBackgroundTask = Task.Run(() => DoComplexCpuWork());

This will offload DoComplexCpuWork to a thread-pool thread, while your main thread (the one that executed Task.Run is free to continue. You can then query the someBackgroundTask to see if it finished whatever it's doing and read the result (if any).

If you want an infinite loop in the background thread, you'd usually use a long-running task - just read through the documentation for Task.Run , it's quite clear.

The second approach is helpful if you're dealing with operations that don't use (much) CPU. For example, you could have an infinite loop that waits on data from a network stream, or just something that copies a file from one place to another. There's no need to waste threads on these, all you need is to use asynchronous APIs (usually something like ReadAllLinesAsync and similar).

As soon as you start dealing with code like this, you must take synchronization into account. The default thinking is always "whatever crosses thread boundaries must be synchronized". You can't just access the same field from two threads and expect it to work anymore.

A great starter about asynchronous code and multi-threading is http://www.albahari.com/threading/ - if you want to deal with any kind of asynchronous or multi-threaded code, you should read through it all. Ideally multiple times. And keep it for reference :P

Note that both are much easier in a graphical UI, like Windows Forms. A typical Windows Forms application has a message loop for asynchronous UI, and you can easily and safely use code like

lblProgress.Text = "Calculating...";

var result = await Task.Run(() => DoWork());

lblProgress.Text = "Calculation done, sending to server.";

await SendDataToServerAsync(result);

lblProgress.Text = "Done.";

to seamlessly handle asynchronous code in a synchronous-looking way, all without blocking the UI. If you want to learn to use await , starting with a UI application is definitely the easier path, because a lot of the infrastructure is already there for free. You'll have to write your own in a console application.

Microsoft recognise the complexity of building multi-threaded applications and the issues that can be caused with multiple thread attempting to access the same data. A class called BackgroundWorker might be the way to go for your application. A very comprehensive tutorial can be found here . I've used it numerous times to achieve the sorts of things your talking about and it benefits from managing much of the more complex threading tasks automatically.

they are all good points. Specially @luaan comprehensive answer. So to complete it all and to answer your question, you can do this:

public void Main()
{
    var backgroundLoop = Task.Run(() =>
    {
        for (int i = 0; i < 10; i++)
        {
            // This will be running in the backgroud
        }
    });

    Console.WriteLine("Continuing with the program while the loop is running. Loop completed? " + backgroundLoop.IsCompleted);

    backgroundLoop.Wait(); // Block here, and Wait until the loop is finished
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM