ThreadPool.RegisterWaitForSingleObject(wait, new WaitOrTimerCallback(test11), state, 5000, false)可以用来在线程完成,或者超时时,调用回调函数。
实例参考:
|
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
|
using
System;
using
System.Threading;
using
static
System.Console;
using
static
System.Threading.Thread;
namespace
Chapter3.Recipe5
{
class
Program
{
static
void
Main(
string
[] args)
{
//RunOperations(TimeSpan.FromSeconds(5));
RunOperations(TimeSpan.FromSeconds(7));
Console.ReadLine();
}
static
void
RunOperations(TimeSpan workerOperationTimeout)
{
using
(
var
evt =
new
ManualResetEvent(
false
))
using
(
var
cts =
new
CancellationTokenSource())
{
WriteLine(
"Registering timeout operation..."
);
var
worker = ThreadPool.RegisterWaitForSingleObject(evt
, (state, isTimedOut) => WorkerOperationWait(cts, isTimedOut)
//超时后,被调用的函数
,
null
, 8000
//超时值
,
true
);
WriteLine(
"Starting long running operation..."
);
ThreadPool.QueueUserWorkItem(_ => WorkerOperation(evt))
//Sleep(workerOperationTimeout.Add(TimeSpan.FromSeconds(2))); //该语句的功能,就是让线程所在的函数没有运行结束,因为线程池中的线程,都是后台线程。
Sleep(15000);
worker.Unregister(evt);
}
}
static
void
WorkerOperation(ManualResetEvent evt)
{
for
(
int
i = 0; i < 2; i++)
{
Sleep(TimeSpan.FromSeconds(1));
}
evt.Set();
}
|
参考链接:
http://www.cnblogs.com/Kazaf/archive/2012/03/26/2417341.html
本文转自daniel8294 51CTO博客,原文链接:http://blog.51cto.com/acadia627/1972587,如需转载请自行联系原作者