-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpAsyncHandler.cs
More file actions
79 lines (64 loc) · 2.25 KB
/
HttpAsyncHandler.cs
File metadata and controls
79 lines (64 loc) · 2.25 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
78
79
using System;
using System.Threading.Tasks;
using System.Web;
//Originally from Com.Hertkorn.TaskBasedIHttpAsyncHandler.Framework
namespace httpTester
{
/// <summary>
/// Root class for HttpAsyncHandler using TPL. Based upon http://www.fsmpi.uni-bayreuth.de/~dun3/archives/task-based-ihttpasynchandler/532.html
/// </summary>
public abstract class HttpAsyncHandler : IHttpAsyncHandler
{
// In very high performance situations you might want to change the argument to HttpContext
// and save one object allocation per request.
public abstract void ProcessRequestAsync(HttpContext context);
public abstract bool IsReusable { get; }
IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
if (cb == null)
{
throw new InvalidOperationException("cb is null");
}
var task = CreateTask(context,cb);
if (task.Status == TaskStatus.Created)
{
// Got a cold task -> start it
task.Start();
}
return task;
}
void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
{
var task = result as Task;
// Await task --> Will throw pending exceptions
// (to avoid an exception being thrown on the finalizer thread)
task.Wait();
task.Dispose();
}
void IHttpHandler.ProcessRequest(HttpContext context)
{
var task = CreateTask(context,null);
if (task.Status == TaskStatus.Created)
{
task.RunSynchronously();
}
else
{
task.Wait();
}
}
public Task CreateTask(HttpContext context,AsyncCallback cb)
{
Task task = new Task(() => ProcessRequestAsync(context));
if (task == null)
{
throw new InvalidOperationException("ProcessRequestAsync must return void");
}
if (cb != null)
{
task.ContinueWith((t) => cb(t));
}
return task;
}
}
}