如何在c#程序中连续运行一个函数

本文关键字:函数 一个 运行 连续 程序 | 更新日期: 2023-09-27 18:12:30

我用c#为Windows 8编写的桌面应用程序来提供剪贴板上不同设备传感器的读数。现在,有一个外部应用程序(我对它的结构没有任何控制),我的应用程序将与之交互。这两个应用程序都使用一个互文本文件作为交换。当外部应用程序需要我的读数时,它会将文本文件重命名为"SensorsTurn.txt",并在剪贴板上添加一个触发词,例如("sensors")。当我的应用程序看到文件被这样命名时,它读取剪贴板中的触发器,收集相应的数据,将其放在剪贴板上,并将文本文件重命名为'RBsTurn.txt'。问题是,我需要我的程序在运行期间不断检查该文件的名称。我想到的一个非常基本的方法是把程序扔进一个无限while循环。但这显然是一个非常糟糕的方法。当我在任务管理器中看到我的应用程序时,它占用了大量的CPU处理,这是不应该的。我发现的另一个建议是让我的循环成为一个后台线程,这样更有效率一些。但是两个连续读数之间的时间变慢了。我的上司报告说:"我第一次尝试写入剪贴板时,它写得非常快,但在随后的写入中,它需要大约3秒(我经常有两个程序与剪贴板通信)。我怀疑您的程序没有以某种方式释放剪贴板。只要我能够写入剪贴板,我就会更改文件名并立即获得您的数据。所以问题源于剪贴板写.... "下面是部分代码:

namespace sampleApplication
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    //Initialize sensor variables
    LightSensorReading _newLightSensorReading;
    LightSensor _LightSensor = LightSensor.GetDefault();
    string _pathString = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "dummy");
    private void Form1_Load(object sender, EventArgs e)
    {
        //InitializeDevices();
        System.IO.Directory.CreateDirectory(_pathString);
        string _filePathSensors = System.IO.Path.Combine(_pathString, "SensorsTurn.txt");
        string _filePathRBsTurn = System.IO.Path.Combine(_pathString, "RBsTurn.txt");
        string _triggerString = "";
        int x = 1;
        Thread th = new Thread(() =>
            {
                while (x == 1)
                {
                    if (System.IO.File.Exists(_filePathSensors))
                    {
                        _triggerString = Clipboard.GetText();
                        switch (_triggerString)
                        {
                            case "sensors":
                                if (_LightSensor != null)
                                {
                                    _newLightSensorReading = _LightSensor.GetCurrentReading();
                                    string _deviceReading = "LightSensor" + "," + _newLightSensorReading.IlluminanceInLux.ToString();
                                    Clipboard.SetText(_deviceReading);
                                    System.IO.File.Move(_filePathSensors, _filePathRBsTurn);
                                }
                                break;
                            case "stop":
                                Clipboard.Clear();
                                System.IO.File.Move(_filePathSensors, _filePathRBsTurn);
                                Application.Exit();
                                break;
                        }
                    }
                }
            });
        th.IsBackground = true;
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }
}
}

长话短说,有两个问题:1)如何连续检查文件名而不使用低效的无限循环?我可以定义一个事件吗?2)我的程序在使用剪贴板后没有足够快地释放它。原因是什么呢?

如何在c#程序中连续运行一个函数

您可以使用File System Watcher对象来响应重命名事件,而不是不断查找更改的名称。这样可以完全避免这个问题。

更新:

这是一篇关于

主题的博客文章(之前在评论中提到过)

正确的做法是创建一个FileSystemWatcher,它将在文件名更改(或创建新文件-在文档中有解释)时引发事件。

当文件被创建或重命名时,将触发一个事件,您可以在处理程序的主体中处理该事件并执行您的操作。

我会使用Timer。这样,您就可以按指定的时间间隔运行,否则不会占用CPU。本质上,它用Thread完成了Thread解决方案。睡眠可以,但以一种更干净,更可读的方式,我想。

using System;
using System.Timers;
public class Timer1
{
    private static System.Timers.Timer aTimer;
    public static void Main()
    {
        // Normally, the timer is declared at the class level, 
        // so that it stays in scope as long as it is needed. 
        // If the timer is declared in a long-running method,   
        // KeepAlive must be used to prevent the JIT compiler  
        // from allowing aggressive garbage collection to occur  
        // before the method ends. You can experiment with this 
        // by commenting out the class-level declaration and  
        // uncommenting the declaration below; then uncomment 
        // the GC.KeepAlive(aTimer) at the end of the method. 
        //System.Timers.Timer aTimer; 
        // Create a timer with a ten second interval.
        aTimer = new System.Timers.Timer(10000);
        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        // Set the Interval to 2 seconds (2000 milliseconds).
        aTimer.Interval = 2000;
        aTimer.Enabled = true;
        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();
        // If the timer is declared in a long-running method, use 
        // KeepAlive to prevent garbage collection from occurring 
        // before the method ends. 
        //GC.KeepAlive(aTimer);
    }
    // Specify what you want to happen when the Elapsed event is  
    // raised. 
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}
/* This code example produces output similar to the following:
Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
 */

只是使用一个无限循环,但在循环结束时,添加一个Thread.Sleep(1000)或类似的东西。这样它就不会占用你所有的CPU时间。

让你的线程调用一个包含while循环的方法