简体   繁体   English

C#同时执行资源监视逻辑和其他任务

[英]C# simultaneous execution of resources-monitoring logic and other tasks

I am developing a program which will run on thin clients with minimum multitasking capabilities and other hardware resources. 我正在开发一个程序,该程序将在具有最少的多任务处理能力和其他硬件资源的瘦客户机上运行。 I wish to have two methods running continuously but not hold the flow of the program. 我希望有两种方法可以连续运行,但不能保留程序的流程。 During my search I came across some posts that try to address similar concepts but they are quite old and either in a different programming language or do not solve my problem. 在我的搜索过程中,我遇到了一些尝试解决类似概念的帖子,但是它们很老,要么使用其他编程语言要么无法解决我的问题。

In my program I have a file system watcher, a resources monitor method, and some other methods. 在我的程序中,我有一个文件系统监视程序,一个资源监视方法以及一些其他方法。

Currently my program runs file system watcher and ResourcesMonitor() method in parallel but the program does not get past ResourcesMonitor() method so the ThirdMethod() and other following methods never execute. 当前,我的程序并行运行文件系统监视程序和ResourcesMonitor()方法,但是该程序没有获得过去的ResourcesMonitor()方法,因此ThirdMethod()和其他后续方法从不执行。

How can I have my program run ResourcesMonitor() and also execute the remaining methods below this method? 如何让我的程序运行ResourcesMonitor()并执行该方法下的其余方法?

class Program
{

    static void Main(string[] args)
    {
        // call the FSW
        var task = MyFileSystemWatcher(path);

        // call another method that works same way as file system watcher
        ResourcesMonitor();  

        // call another method
        ThirdMethod();

        // more methods
    }

    private void ResourcesMonitor()
    {

        // on a thin client with limited hardware resources

        using (an API)
        {
            // monitors...
        // if number of processes is higher than recommended, close some uncessary background processes
        // in the cases of resources overflow, write to log


            // to have the this method run infinitely
            System.Windows.Forms.Application.Run();
        }
    }

    private static void ThirdMethod()
    {
        // does something
    }

    private static async Task MyFileSystemWatcher(string path)
    {
        // file system watcher
    }

}

Currently I have two such methods but may have more methods with a similar logic later that I will have to run in parrallel. 目前,我有两种这样的方法,但是以后可能会有更多具有类似逻辑的方法必须并行运行。

You can use Task to accomplish this: 您可以使用Task来完成此Task

    // call another method that works same way as file system watcher
    var task1 = Task.Run(() => ResourcesMonitor());

    // call another method
    var task2 = Task.Run(() => ThirdMethod());


    Task.WaitAll(new { task1, task2 } );

使用所需的方法创建新线程,可以选择使其成为后台,并根据需要分配优先级(有多个)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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