Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit47263d6

Browse files
committed
1.添加生产者消费者
1 parent0459955 commit47263d6

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
usingSystem;
2+
usingSystem.Collections.Generic;
3+
usingSystem.Linq;
4+
usingSystem.Text;
5+
usingSystem.Threading;
6+
usingSystem.Threading.Tasks;
7+
8+
namespaceDestiny.Core.Flow.Shared
9+
{
10+
11+
12+
/// <summary>
13+
/// 生产者消费者
14+
/// </summary>
15+
publicclassProducerConsumerQueue:IDisposable
16+
{
17+
18+
publicEventHandlerEventHandler=null;
19+
EventWaitHandlewh=newAutoResetEvent(false);
20+
Threadworker;
21+
Queue<string>tasks=newQueue<string>();
22+
23+
readonlyobject_locker=newobject();
24+
25+
publicProducerConsumerQueue()
26+
{
27+
28+
worker=newThread(Work);
29+
worker.Start();
30+
}
31+
32+
publicvoidEnqueueTask(stringtask)
33+
{
34+
lock(_locker)
35+
{
36+
37+
tasks.Enqueue(task);
38+
}
39+
wh.Set();
40+
}
41+
42+
43+
publicvoidWork()
44+
{
45+
while(true)
46+
{
47+
stringtask=null;
48+
lock(_locker)
49+
{
50+
if(tasks.Count>0)
51+
{
52+
task=tasks.Dequeue();
53+
if(task==null)
54+
{
55+
return;
56+
}
57+
}
58+
59+
}
60+
61+
if(task!=null)
62+
{
63+
64+
if(EventHandler!=null)
65+
{
66+
EventHandler.Invoke(task,null);
67+
Thread.Sleep(1000);
68+
69+
}
70+
71+
}
72+
else
73+
{
74+
wh.WaitOne();
75+
}
76+
77+
}
78+
79+
80+
}
81+
82+
publicvoidDispose()
83+
{
84+
// 消费者退出信号
85+
EnqueueTask(null);
86+
87+
// 等待消费者线程结束
88+
worker.Join();
89+
90+
wh.Close();
91+
}
92+
}
93+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp