Repository navigation
Expand file tree
/
Copy pathStringBuilderPoolTests.cs
More file actions
77 lines (70 loc) · 1.87 KB
/
Copy pathStringBuilderPoolTests.cs
File metadata and controls
77 lines (70 loc) · 1.87 KB
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
using System.Threading;
using System.Threading.Tasks;
using ICSharpCode.SharpZipLib.Core;
using NUnit.Framework;
namespace ICSharpCode.SharpZipLib.Tests.Core
{
[TestFixture]
public class StringBuilderPoolTests
{
[Test]
[Category("Core")]
public void RoundTrip()
{
var pool = new StringBuilderPool();
var builder1 = pool.Rent();
pool.Return(builder1);
var builder2 = pool.Rent();
Assert.AreEqual(builder1, builder2);
}
[Test]
[Category("Core")]
public void ReturnsClears()
{
var pool = new StringBuilderPool();
var builder1 = pool.Rent();
builder1.Append("Hello");
pool.Return(builder1);
Assert.AreEqual(0, builder1.Length);
}
[Test]
[Category("Core")]
public async Task ThreadSafeAsync()
{
// use a lot of threads to increase the likelihood of errors
var concurrency = 100;
var pool = new StringBuilderPool();
var gate = new TaskCompletionSource<bool>();
var startedTasks = new Task[concurrency];
var completedTasks = new Task<string>[concurrency];
for (int i = 0; i < concurrency; i++)
{
var started = new TaskCompletionSource<bool>();
startedTasks[i] = started.Task;
var captured = i;
completedTasks[i] = Task.Run(async () =>
{
started.SetResult(true);
await gate.Task;
var builder = pool.Rent();
builder.Append("Hello ");
builder.Append(captured);
var str = builder.ToString();
pool.Return(builder);
return str;
});
}
// make sure all the threads have started
await Task.WhenAll(startedTasks);
// let them all loose at the same time
gate.SetResult(true);
// make sure every thread produces the expected string and hence had its own StringBuilder
var results = await Task.WhenAll(completedTasks);
for (int i = 0; i < concurrency; i++)
{
var result = results[i];
Assert.AreEqual($"Hello {i}", result);
}
}
}
}