-
Notifications
You must be signed in to change notification settings - Fork 1
/
DataGenerator.cs
83 lines (73 loc) · 2.31 KB
/
DataGenerator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
namespace FileWriter
{
internal class DataGenerator
{
string myDirectory;
const int KB = 1024;
/// <summary>
/// Make Virus scanner nervous
/// </summary>
string myFileExtension = ".cmd";
public DataGenerator(string dir, string extension)
{
myFileExtension = extension;
if( !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
else
{
// delete old test data
foreach(var file in Directory.GetFiles(dir, "*" + myFileExtension))
{
File.Delete(file);
}
}
myDirectory = dir;
}
public void CreateFiles(int n, int sizeKB)
{
for(int i = 0; i < n; i++)
{
CreateFile(i, sizeKB);
}
}
public void CreateFilesParallel(int n, int sizeKB, int? nThreads)
{
ParallelOptions options = new ParallelOptions();
if( nThreads != null)
{
options.MaxDegreeOfParallelism = nThreads.Value;
}
Parallel.For(0, n, options, i => CreateFile(i, sizeKB));
}
public void CreateFilesTask(int n, int sizekB)
{
List<Task> tasks = new List<Task>();
for(int i= 0; i < n; i++)
{
int captured = i;
tasks.Add( Task.Run( () => CreateFile(captured, sizekB)));
}
Task.WaitAll(tasks.ToArray());
}
private void CreateFile(int i, int sizeKB)
{
int lineCount = 1;
int writtenBytes = 0;
string fileName = Path.Combine(myDirectory, $"TestDataFile_{i}{myFileExtension}");
using(FileStream fs = new FileStream(fileName, FileMode.Create))
{
using(StreamWriter sw = new StreamWriter(fs))
{
while (writtenBytes < sizeKB * KB)
{
string line = $"echo This is line {lineCount++}";
sw.WriteLine(line);
writtenBytes += line.Length;
}
}
}
}
}
}