Skip to content

Commit d16dba3

Browse files
committed
update
1 parent a0dc04a commit d16dba3

File tree

1 file changed

+96
-37
lines changed

1 file changed

+96
-37
lines changed

Diff for: README.md

+96-37
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,17 @@ string result = shape switch
3737
Circle c => $"Circle: ({c.X}, {c.Y}), radius {c.Radius}",
3838
_ => "Unknown shape"
3939
};
40-
// list (prior or dotnet 8)
40+
```
41+
# Collection
42+
```
43+
// prior to dotnet 8
4144
int[] numbers = { 1, 2, 3, 4, 5 };
42-
// list (from dotnet 8)
43-
int[] numbers = [ 1, 2, 3, 4, 5];
45+
46+
// from dotnet 8
47+
int[] first = [ 1, 2, 3, 4, 5];
48+
int[] second = [6, 7];
49+
50+
var both = [..first, ..second];
4451
```
4552
# Raw String Literals
4653
```
@@ -76,30 +83,6 @@ await task;
7683
```
7784
using `TaskCompletionSource<T>`
7885
```
79-
class CustomerService : IRecipient<CustomerResultMessage>
80-
{
81-
private TaskCompletionSource<Customer> _tcs;
82-
83-
public CustomerService()
84-
{
85-
WeakReferenceMessenger.Default.Register<CustomerResultMessage>(this);
86-
}
87-
88-
public Task<Customer> GetCustomerAsync()
89-
{
90-
_tcs = new TaskCompletionSource<Customer>();
91-
// send a message (note: set result when receive CustomerResultMessage)
92-
WeakReferenceMessenger.Default.Send(new GetCustomerMessage(1));
93-
return _tcs.Task;
94-
}
95-
96-
public void Receive(CustomerResultMessage message)
97-
{
98-
_tcs.SetResult(message.Customer)
99-
}
100-
}
101-
```
102-
```
10386
TaskCompletionSource<int> tcs = new ();
10487
10588
// Start a separate task that simulates an asynchronous operation
@@ -117,6 +100,43 @@ Task.Run(() =>
117100
// Await the task from TaskCompletionSource
118101
int result = await tcs.Task;
119102
```
103+
using `CancellationToken`
104+
```
105+
sealed class SomeService
106+
{
107+
private TaskCompletionSource<int> _tcs;
108+
private CancellationToken _token;
109+
110+
public Task<int> DoSomethingAsync(CancellationToken token)
111+
{
112+
_tcs = new TaskCompletionSource<int>();
113+
_token = token;
114+
// run something in background
115+
Task.Run(MyAction);
116+
return _tcs.Task;
117+
}
118+
119+
public void MyAction()
120+
{
121+
for(var i = 0; i<1000000; i++)
122+
{
123+
// do something
124+
Thread.Sleep(10);
125+
_token.ThrowIfCancellationRequested();
126+
}
127+
// set the result
128+
_tcs.SetResult(100);
129+
}
130+
}
131+
132+
// usage (create service, run task and cancel it after 1 second)
133+
var s = new SomeService();
134+
var cancellationTokenSource = new CancellationTokenSource();
135+
var task = s.DoSomethingAsync(cancellationTokenSource.Token);
136+
await Task.Delay(1000);
137+
cancellationTokenSource.Cancel(); // OperationCanceledException would occurred here
138+
```
139+
120140
## Send messages via `WeakReferenceMessenger`
121141
declare message
122142
```
@@ -201,9 +221,9 @@ var app = builder.Build();
201221
app.UseExceptionHandler();
202222
```
203223

204-
## prior to dotnet 8 via middleware
224+
## prior to dotnet 8 via convention based middleware
205225
```
206-
public class GlobalExceptionHandlerMiddleware
226+
public sealed class GlobalExceptionHandlerMiddleware
207227
{
208228
private readonly RequestDelegate _next;
209229
private readonly ILogger<GlobalExceptionHandlerMiddleware> _logger;
@@ -220,26 +240,65 @@ public class GlobalExceptionHandlerMiddleware
220240
{
221241
try
222242
{
243+
// execute code before request
244+
223245
await _next(context);
246+
247+
// execute code after request
224248
}
225249
catch (Exception ex)
226250
{
227251
// Handle exceptions here
228-
await HandleExceptionAsync(context, ex);
252+
logger.LogError(ex, "Unhandled error");
253+
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
254+
context.Response.ContentType = "application/json";
255+
await context.Response.WriteAsync("{ code = 123, error = \"server error\" }");
229256
}
230257
}
258+
}
259+
```
260+
register
261+
```
262+
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
263+
```
264+
265+
## prior to dotnet 8 via Factory based middleware
266+
```
267+
public sealed class GlobalExceptionHandlerMiddleware : IMiddleware
268+
{
269+
private readonly ILogger<GlobalExceptionHandlerMiddleware> _logger;
270+
271+
public GlobalExceptionHandlerMiddleware(ILogger<GlobalExceptionHandlerMiddleware> logger)
272+
{
273+
_logger = logger;
274+
}
231275
232-
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
276+
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
233277
{
234-
logger.LogError(exception, "Unhandled error");
235-
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
236-
context.Response.ContentType = "application/json";
237-
await context.Response.WriteAsync("{ code = 123, error = \"server error\" }");
278+
try
279+
{
280+
// execute code before request
281+
282+
await next(context);
283+
284+
// execute code after request
285+
}
286+
catch (Exception ex)
287+
{
288+
// Handle exceptions here
289+
logger.LogError(ex, "Unhandled error");
290+
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
291+
context.Response.ContentType = "application/json";
292+
await context.Response.WriteAsync("{ code = 123, error = \"server error\" }");
293+
}
238294
}
239295
}
240296
```
241-
242-
## prior to dotnet 8
297+
register
298+
```
299+
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
300+
```
301+
## prior to dotnet 8 via request delegate based middleware
243302
```
244303
app.UseExceptionHandler(errorApp =>
245304
{

0 commit comments

Comments
 (0)