C# 等待的FileSystemWatcher结果

C# 等待的FileSystemWatcher结果,c#,C#,我已经围绕文件系统观察者创建了一个包装类。该类的目的是等待创建文本文件,然后将文件内容读入其\u结果字段 我想在类中添加一个名为GetResultAsync()的方法,这样调用者就可以等待结果准备就绪,但我不知道如何最好地进行。请有人给我指一下正确的方向好吗 internal class SingleFileWatcher : IDisposable { private readonly string _targetFile; private readonly FileSyste

我已经围绕
文件系统观察者创建了一个包装类。该类的目的是等待创建文本文件,然后将文件内容读入其
\u结果
字段

我想在类中添加一个名为
GetResultAsync()
的方法,这样调用者就可以
等待结果准备就绪,但我不知道如何最好地进行。请有人给我指一下正确的方向好吗

internal class SingleFileWatcher : IDisposable
{
    private readonly string _targetFile;
    private readonly FileSystemWatcher _fileWatcher;
    private string _result = null;

    internal SingleFileWatcher(string theFile)
    {
        _targetFile = theFile;

        _fileWatcher = new FileSystemWatcher();
        _fileWatcher.Path = Path.GetDirectoryName(theFile);
        _fileWatcher.Filter = Path.GetFileName(theFile);
        _fileWatcher.IncludeSubdirectories = false;
        _fileWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
        _fileWatcher.Created += FileCreated;

        if (File.Exists(theFile))
        {
            ProcessFile();
        }
        else
        {
            //this must happen after other members have been set
            _fileWatcher.EnableRaisingEvents = true;
        }
    }

    internal Task<string> GetResultAsync()
    {
        //todo
    }

    private void FileCreated(Object sender, FileSystemEventArgs e)
    {
        ProcessFile();
    }

    private void ProcessFile()
    {

        FileStream stream = null;

        //filecreated is raised as soon as the file is created, but the process may still be writing to the file
        while (true)
        {
            try
            {
                stream = new FileStream(_targetFile, FileMode.Open, FileAccess.Read);

                using (var reader = new StreamReader(stream))
                {
                    stream = null;
                    _result = reader.ReadToEnd();
                }

                break;
            }
            catch (IOException)
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(500));
            }
            finally
            {
                stream?.Dispose();
            }
        }
    }

    public void Dispose()
    {
        _fileWatcher.Created -= FileCreated;
        _fileWatcher.Dispose();
    }
}
内部类SingleFileWatcher:IDisposable
{
私有只读字符串_targetFile;
私有只读文件系统监视程序\u文件监视程序;
私有字符串_result=null;
内部SingleFileWatcher(字符串文件)
{
_targetFile=theFile;
_fileWatcher=新的FileSystemWatcher();
_fileWatcher.Path=Path.GetDirectoryName(文件);
_fileWatcher.Filter=Path.GetFileName(文件);
_fileWatcher.IncludeSubdirectories=false;
_fileWatcher.NotifyFilter=NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
_fileWatcher.Created+=FileCreated;
if(File.Exists(文件))
{
ProcessFile();
}
其他的
{
//这必须在设置其他成员后进行
_fileWatcher.EnableRaisingEvents=true;
}
}
内部任务GetResultAsync()
{
//待办事项
}
已创建私有无效文件(对象发送方、文件系统目标)
{
ProcessFile();
}
私有void进程文件()
{
FileStream=null;
//filecreated会在创建文件后立即引发,但进程可能仍在写入文件
while(true)
{
尝试
{
stream=新文件流(_targetFile,FileMode.Open,FileAccess.Read);
使用(变量读取器=新的流读取器(流))
{
流=空;
_结果=reader.ReadToEnd();
}
打破
}
捕获(IOException)
{
睡眠(时间跨度从毫秒(500));
}
最后
{
流?.Dispose();
}
}
}
公共空间处置()
{
_fileWatcher.Created-=FileCreated;
_Dispose();
}
}

扩展Jeroen Mosterts评论。您的代码应该如下所示:

internal Task<string> GetResultAsync()
{
    var tcs = new TaskCompletionSource<string>();
    ProcessFile();
    tcs.TrySetResult(_result);
    return tcs.Task;
}
内部任务GetResultAsync()
{
var tcs=new TaskCompletionSource();
ProcessFile();
tcs.TrySetResult(_result);
返回tcs.Task;
}
这是非常幼稚的,我建议您考虑异常处理和取消的场景。它们应该在
ProcessFile
中,因此它看起来像
taskprocessfile(taskcompletionsourcetcs)

要设置异常,请使用
tcs.TrySetException(异常)

TaskCompletionSource
可能是您的朋友。谢谢,TaskCompletionSource帮我解决了这个问题。