forked from tunnelvisionlabs/dotnet-threading
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTaskBlockUsingWithResult.cs
More file actions
67 lines (59 loc) · 2.26 KB
/
Copy pathTaskBlockUsingWithResult.cs
File metadata and controls
67 lines (59 loc) · 2.26 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
// Copyright (c) Rackspace, US Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace CSharpSamples
{
using System;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rackspace.Threading;
using StringReader = System.IO.StringReader;
/// <summary>
/// This class contains unit-tested example code for the <see cref="TaskBlocks.Using{TResource, TResult}(Func{Task{TResource}}, Func{Task{TResource}, Task{TResult}})"/>
/// building block method.
/// </summary>
[TestClass]
public class TaskBlockUsingWithResult
{
private const string SampleText = "Text to read";
[TestMethod]
public async Task TestUsingWithResultAsyncAwait()
{
string text = await UsingWithResultAsyncAwait();
Assert.AreEqual(SampleText, text);
}
[TestMethod]
public async Task TestUsingWithResultAsyncBuildingBlock()
{
string text = await UsingWithResult();
Assert.AreEqual(SampleText, text);
}
#pragma warning disable 1998 // This async method lacks 'await' operators and will run synchronously....
#region UsingWithResultAsyncAwait
public async Task<string> UsingWithResultAsyncAwait()
{
using (StringReader resource = await AcquireResourceAsyncAwait())
{
return await resource.ReadToEndAsync();
}
}
private async Task<StringReader> AcquireResourceAsyncAwait()
{
// this would generally contain an asynchronous call
return new StringReader("Text to read");
}
#endregion
#pragma warning restore 1998
#region UsingWithResultAsyncBuildingBlock
public Task<string> UsingWithResult()
{
return TaskBlocks.Using(
() => AcquireResourceAsync(),
task => task.Result.ReadToEndAsync());
}
private Task<StringReader> AcquireResourceAsync()
{
// this would generally contain an asynchronous call
return CompletedTask.FromResult(new StringReader("Text to read"));
}
#endregion
}
}