using System.Text;
public class Example
{
public async static Task Main()
{
ProcessMulitpleWritesAsync().GetAwaiter().GetResult();
}
public async static Task ProcessMulitpleWritesAsync()
{
IList<FileStream> sourceStreams = new List<FileStream>();
try
{
// Testfolder 생성
string folder = Directory.CreateDirectory("Testfolder").Name;
IList<Task> writeTaskList = new List<Task>();
// 10개의 파일을 Async로 생성.
for (int index = 1; index <= 10; ++index)
{
string fileName = $"codekiller-{index:00}.txt";
string filePath = $"{folder}/{fileName}";
string text = $"In file {index}{Environment.NewLine}";
byte[] encodedText = Encoding.Unicode.GetBytes(text);
var sourceStream =
new FileStream(filePath,FileMode.Create, FileAccess.Write, FileShare.None,bufferSize: 4096, useAsync: true);
Task writeTask = sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
sourceStreams.Add(sourceStream);
writeTaskList.Add(writeTask);
}
// Task 완료 대기.
await Task.WhenAll(writeTaskList);
}
finally
{
foreach (FileStream sourceStream in sourceStreams)
{
sourceStream.Close();
}
}
}
}