@@ -37,10 +37,17 @@ string result = shape switch
37
37
Circle c => $"Circle: ({c.X}, {c.Y}), radius {c.Radius}",
38
38
_ => "Unknown shape"
39
39
};
40
- // list (prior or dotnet 8)
40
+ ```
41
+ # Collection
42
+ ```
43
+ // prior to dotnet 8
41
44
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];
44
51
```
45
52
# Raw String Literals
46
53
```
@@ -76,30 +83,6 @@ await task;
76
83
```
77
84
using ` TaskCompletionSource<T> `
78
85
```
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
- ```
103
86
TaskCompletionSource<int> tcs = new ();
104
87
105
88
// Start a separate task that simulates an asynchronous operation
@@ -117,6 +100,43 @@ Task.Run(() =>
117
100
// Await the task from TaskCompletionSource
118
101
int result = await tcs.Task;
119
102
```
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
+
120
140
## Send messages via ` WeakReferenceMessenger `
121
141
declare message
122
142
```
@@ -201,9 +221,9 @@ var app = builder.Build();
201
221
app.UseExceptionHandler();
202
222
```
203
223
204
- ## prior to dotnet 8 via middleware
224
+ ## prior to dotnet 8 via convention based middleware
205
225
```
206
- public class GlobalExceptionHandlerMiddleware
226
+ public sealed class GlobalExceptionHandlerMiddleware
207
227
{
208
228
private readonly RequestDelegate _next;
209
229
private readonly ILogger<GlobalExceptionHandlerMiddleware> _logger;
@@ -220,26 +240,65 @@ public class GlobalExceptionHandlerMiddleware
220
240
{
221
241
try
222
242
{
243
+ // execute code before request
244
+
223
245
await _next(context);
246
+
247
+ // execute code after request
224
248
}
225
249
catch (Exception ex)
226
250
{
227
251
// 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\" }");
229
256
}
230
257
}
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
+ }
231
275
232
- private async Task HandleExceptionAsync (HttpContext context, Exception exception )
276
+ public async Task InvokeAsync (HttpContext context, RequestDelegate next )
233
277
{
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
+ }
238
294
}
239
295
}
240
296
```
241
-
242
- ## prior to dotnet 8
297
+ register
298
+ ```
299
+ app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
300
+ ```
301
+ ## prior to dotnet 8 via request delegate based middleware
243
302
```
244
303
app.UseExceptionHandler(errorApp =>
245
304
{
0 commit comments