我正在编写一个具有FileSystemWatcher的程序。我还想与FSW一起运行另外两种方法。但是我的其他方法无法执行,因为程序始终在FSW上。
本质上,我希望FileSystemWatcher继续运行并能够在我的程序中同时执行其他操作。
如何构造代码来实现这一目标?
当前,我的代码具有以下结构:
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
// call the FSW
MyFileSystemWatcher(path);
// call another method
AnotherMethod1();
// call another method
AnotherMethod2();
}
//----- file system watcher methods -----//
private static void MyFileSystemWatcher(string path)
{
// code for the file system watcher
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
fileSystemWatcher.Path = path;
fileSystemWatcher.Created += FileSystemWatcher_Created;
fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;
fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;
fileSystemWatcher.EnableRaisingEvents = true;
}
private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File created: {0}", e.Name);
}
private static void FileSystemWatcher_Renamed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File renamed: {0}", e.Name);
}
private static void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File deleted: {0}", e.Name);
}
//----- end of file system watcher methods -----//
//----- other methods in the program -----//
public static void AnotherMethod1()
{
// code for Method1
}
private static void AnotherMethod2()
{
// code for Method2
}
}
}
谢谢。
答案 0 :(得分:1)
使您的方法异步
x
然后
private static async Task MyFileSystemWatcher(string path)
{
// code for the file system watcher
}
或者,如果您不想碰触您的方法(不理想),那么
static void Main(string[] args)
{
// call the File System Watcher
var task = MyFileSystemWatcher(path);
// call another method
AnotherMethod1();
// call another method
AnotherMethod2();
}