C# 在后台运行一个循环 [英] C# Run a loop in the background

查看:55
本文介绍了C# 在后台运行一个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个程序,该程序有一个名为number"的 int 变量,我想制作一个后台循环,将number"加 1,同时我在主程序中进行一些计算.我知道我需要使用线程,我试过但它不起作用.你能帮我解决吗?非常感谢!

Lets say I have a program, this program has an int variable named 'number', and I want to make a background loop that will add 1 to 'number', while im doing some calculations in the main program. I know I need to use Threading, I tried but it does'nt work. Can you help me out with it? Thank you very much!

推荐答案

该程序将产生一个单独的线程.您可以使用自己的代码轻松替换我的两个循环.

This program will spawn a separate thread. You can easily replace my two loops with your own code.

using System;
using System.Threading;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            var ts = new ThreadStart(BackgroundMethod);
            var backgroundThread = new Thread(ts);
            backgroundThread.Start();

            // Main calculations here.
            int j = 10000;
            while (j > 0)
            {
                Console.WriteLine(j--);
            }
            // End main calculations.
        }

        private static void BackgroundMethod()
        {
            // Background calculations here.
            int i = 0;
            while (i < 100000)
            {
                Console.WriteLine(i++);
            }
            // End background calculations.
        }
    }
}

这篇关于C# 在后台运行一个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆