1 c# multithreading windows-services timer
我创建了一个Windows服务,它将不时检查某个是否存在,如果存在,则从中读取,将数据发送到服务器并将文件移动到另一个文件夹.文件大小约为1-3 Mb.
我想我会System.Threading.Timer
在这里用来检查文件是否存在.你怎么看呢?
另一个问题.如果正在复制文件,则我的应用程序不得从中读取.它应该等到复制完成.只有在那之后它必须从中读取并进行其他活动.
所以问题:
1)这是一个正确的决定System.Threading.Timer
吗?
2)如何检查文件是否被复制并等待文件完成?
3)我必须使用多线程吗?
我想我会
System.Threading.Timer
在这里用来检查文件是否存在.你怎么看呢?
我想你可能会看一下这个FileSystemWatcher
类会在创建文件时通知你并引发一个事件而不是你使用一个Timer来连续轮询该文件是否存在.
定时器非常昂贵。您可以使用FileSystemWatcher
which 侦听文件系统更改通知并在目录或目录中的文件更改时引发事件。
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = /*path*/
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
Run Code Online (Sandbox Code Playgroud)
那么这将是OnChanged
方法:
//This method is called when a file is created, changed, or deleted.
private static void OnChanged(object source, FileSystemEventArgs e)
{
//Show that a file has been created, changed, or deleted.
WatcherChangeTypes wct = e.ChangeType;
Console.WriteLine("File {0} {1}", e.FullPath, wct.ToString());
}
Run Code Online (Sandbox Code Playgroud)
参考:http : //devproconnections.com/net-framework/how-build-folder-watcher-service-c