이 아마 정확하게 당신이 필요로하는 프로그램의 흐름을 보여주지 않는다. 관심이 있지만, 그것은 당신이 읽는주고 늘 당신의 UI (비동기)를 중지 쓰기 않습니다. 잘하면 당신이 필요로하는 것을 적응시킬 수있을 것입니다.
public class AsyncFileUpdate
{
object locker = new object();
public FileInfo File { get; private set; }
public AsyncFileUpdate(FileInfo file)
{
File = file;
}
/// <summary>
/// Reads contents of a file asynchronously.
/// </summary>
/// <returns>A task representing the asynchronous operation</returns>
public Task<string> ReadFileAsync()
{
return Task.Factory.StartNew<string>(() =>
{
lock (locker)
{
using (var fs = File.OpenRead())
{
StreamReader reader = new StreamReader(fs);
using (reader)
{
return reader.ReadToEnd();
}
}
}
});
}
/// <summary>
/// write file asynchronously
/// </summary>
/// <param name="content">string to write</param>
/// <returns>A task representing the asynchronous operation</returns>
public Task WriteFileAsync(string content)
{
return Task.Factory.StartNew(() =>
{
lock (locker)
{
using (var fs = File.OpenWrite())
{
StreamWriter writer = new StreamWriter(fs);
using (writer)
{
writer.Write(content);
writer.Flush();
}
}
}
});
}
}
/// <summary>
/// Demonstrates usage
/// </summary>
public class FileOperations
{
public void ProcessAndUpdateFile(FileInfo file)
{
AsyncFileUpdate fu = new AsyncFileUpdate(file); ;
fu.ReadFileAsync()
.ContinueWith(p => Process(p.Result))
.ContinueWith(p => fu.WriteFileAsync(p.Result));
}
/// <summary>
/// does the processing on the file content
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
string Process(string content)
{
throw new NotImplementedException("you do this bit ;)");
}
}
이 모든 Task
사업은 작업 병렬 라이브러리에서입니다 - 병렬 및 비동기 프로그래밍 밖으로 hastle을 복용위한 훌륭한 도구 키트. http://msdn.microsoft.com/en-us/library/dd537608.aspx
참고 : 파일 시스템 액세스는 다소 비싸고 물리적으로 저장 매체로 저하됩니다. 이 파일을 관리하고 있습니까 (작성합니까)? 매 초마다 파일을 업데이트하는 것은 아주 금지됩니다. 검사하는 동안 파일이 바뀌는 것에 대해 걱정이된다면 먼저 파일을 복사해야 할 필요가있을 것입니다.
파일을 변경하는 동안 파일을 읽을 수있는 확실한 방법이 없다고 생각합니다 ... –
로그 파일 읽기? – DevZer0
변화하는 파일을 읽는 것은 그것이 사용되는 동안 파일을 잠그지 않는 어떤 종류의 읽기 전용 옵션을 사용해야 할 것입니다. 마찬가지로, 로그 파일에 기록 할 수 있어야합니다. 로그 파일을 작성하는 경우 로그를 쓰는 응용 프로그램이 사용 중이므로 변경 권한이 없을 수 있습니다. 마지막으로, 귀하의 질문은 명확하지 않습니다 - 파일을 어떻게 수정 하시겠습니까? – Shaamaan