Выбор метода для модели Поставщик/получатель
29.07.2017, 15:40. Показов 725. Ответов 0
У меня есть класс-поставщик данных, от которого я получаю данные, подписавшись на соответствующее событие. Желательно как можно быстрее освободить контекст обработчика события, чтобы класс-поставщик мог как можно быстрее вернуться к получению данных от сервера. Моя же обработка поступивших данных может затянуться, т.к. в худшем случае может быть перезаписан файл на несколько мегабайт. Поэтому ранее мне рекомендовали использовать Task'и для своих обработок, но возникает очень много проблем из-за того, что Task'и обрабатываются не всегда в порядке создания.
Нашёл хороший талмуд по этой теме: http://www.albahari.com/threading/ Автор в нескольких главах демонстрирует примеры обработки очереди сообщений в модели Поставщик/получатель. По мотивам его примеров я накидал сводный тест:
Кликните здесь для просмотра всего текста
| C# | 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
| using System;
using System.Threading;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace QueueTest
{
class Program
{
static void Main(string[] args)
{
string value;
// Sample 1
Console.WriteLine("Sample 1: Concurrent queue\r\n{0}", "".PadRight(26, '-'));
ConcurrentQueueSample queue1 = new ConcurrentQueueSample();
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "1");
queue1.Put(value);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "2");
queue1.Put(value);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "3");
queue1.Put(value);
Thread.Sleep(2500);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "4");
queue1.Put(value);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "5");
queue1.Put(value);
queue1.Dispose();
while (!queue1.IsCompleted)
{
Console.Write(".");
Thread.Sleep(50);
}
Console.WriteLine("Press any key...");
Console.ReadLine();
// Sample 2
Console.WriteLine("Sample 2: AutoResetEvent\r\n{0}", "".PadRight(26, '-'));
AutoResetEventSample queue2 = new AutoResetEventSample();
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "1");
queue2.Put(value);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "2");
queue2.Put(value);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "3");
queue2.Put(value);
Thread.Sleep(5000);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "4");
queue2.Put(value);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "5");
queue2.Put(value);
queue2.Stop();
Console.WriteLine("Press any key...");
Console.ReadLine();
// Sample 3
Console.WriteLine("Sample 3: Wait and Pulse\r\n{0}", "".PadRight(26, '-'));
WaitPulseSample queue3 = new WaitPulseSample();
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "1");
queue3.Put(value);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "2");
queue3.Put(value);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "3");
queue3.Put(value);
Thread.Sleep(2500);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "4");
queue3.Put(value);
Console.WriteLine("Current thread: {0}, put: {1}", Thread.CurrentThread.ManagedThreadId, value = "5");
queue3.Put(value);
queue3.Stop();
Console.WriteLine("Press any key...");
Console.ReadLine();
}
}
public class ConcurrentQueueSample : IDisposable
{
// ConcurrentQueue by default
private readonly BlockingCollection<string> _queue = new BlockingCollection<string>();
private readonly Thread _worker;
public bool IsCompleted {
get {
return _queue.IsCompleted;
}
}
public ConcurrentQueueSample ()
{
_worker = new Thread(Work);
_worker.Start();
}
public void Dispose()
{
Console.WriteLine("Completing: {0:O}", DateTime.UtcNow);
_queue.CompleteAdding();
_worker.Join();
Console.WriteLine("Complete: {0:O}", DateTime.UtcNow);
}
public void Put (string element)
{
_queue.Add(element);
}
private void Work()
{
// Последовательность, которую мы перебираем будет заблокирована,
// когда не будет доступных элементов, и завершится после выззова.
foreach (string value in _queue.GetConsumingEnumerable())
{
// Выполняем задачу.
Console.WriteLine("Current thread: {0}, get: {1}, time: {2}",
Thread.CurrentThread.ManagedThreadId, value, DateTime.UtcNow.Ticks);
Thread.Sleep(1000);
}
}
}
public class AutoResetEventSample
{
private readonly EventWaitHandle _waitHandle = new AutoResetEvent(false);
private readonly Queue<string> _queue = new Queue<string>();
private object _locker = new object();
private readonly Thread _worker;
public AutoResetEventSample()
{
//Console.WriteLine(Thread.CurrentThread.Priority);
_worker = new Thread(Work); // {Priority = ThreadPriority.BelowNormal};
_worker.Start();
}
public void Put(string value)
{
lock (_locker)
{
_queue.Enqueue(value);
}
_waitHandle.Set();
}
public void Stop()
{
lock (_locker)
_queue.Enqueue(null);
_waitHandle.Set();
_worker.Join();
}
private void Work()
{
int counter = 0;
while (true)
{
string value = null;
lock (_locker)
{
if (_queue.Count > 0)
{
value = _queue.Dequeue();
if (value == null)
{
//Console.WriteLine(Thread.CurrentThread.Priority);
return;
}
}
else
{
Console.WriteLine("Current thread: {0}, get. Empty queue. Time: {0}, {1,2}",
Thread.CurrentThread.ManagedThreadId, DateTime.UtcNow.Ticks, value == null);
}
}
if (value != null)
{
Console.WriteLine("Current thread: {0}, get: {1}, time: {2}, counter: {3}",
Thread.CurrentThread.ManagedThreadId, value, DateTime.UtcNow.Ticks, counter);
Thread.Sleep(1000);
}
else
{
Console.WriteLine("WaitOne()");
_waitHandle.WaitOne();
}
counter++;
}
}
}
public class WaitPulseSample
{
private readonly Queue<string> _queue = new Queue<string>();
private object _locker = new object();
private readonly Thread _worker;
public WaitPulseSample()
{
_worker = new Thread(Work);
_worker.Start();
}
public void Put(string value)
{
lock (_locker)
{
_queue.Enqueue(value); // We must pulse because we're
Monitor.Pulse (_locker); // changing a blocking condition.
}
}
public void Stop()
{
Put(null);
_worker.Join();
}
private void Work()
{
int counter = 0;
while (true) // Keep consuming until
{ // told otherwise.
string value;
lock (_locker)
{
while (_queue.Count == 0) Monitor.Wait (_locker);
value = _queue.Dequeue();
}
if (value == null) return; // This signals our exit.
Console.WriteLine("Current thread: {0}, get: {1}, time: {2}, counter: {3}",
Thread.CurrentThread.ManagedThreadId, value, DateTime.UtcNow.Ticks, counter);
Thread.Sleep(1000);
counter++;
}
}
}
} |
|
Вывод:
Кликните здесь для просмотра всего текста
| Code | 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
| Sample 1: Concurrent queue
--------------------------
Current thread: 1, put: 1
Current thread: 1, put: 2
Current thread: 1, put: 3
Current thread: 3, get: 1, time: 636369278619323830
Current thread: 3, get: 2, time: 636369278629328120
Current thread: 3, get: 3, time: 636369278639329020
Current thread: 1, put: 4
Current thread: 1, put: 5
Completing: 2017-07-29T12:24:24.4299500Z
Current thread: 3, get: 4, time: 636369278649329920
Current thread: 3, get: 5, time: 636369278659332410
Complete: 2017-07-29T12:24:26.9335990Z
Press any key...
Sample 2: AutoResetEvent
--------------------------
Current thread: 1, put: 1
Current thread: 1, put: 2
Current thread: 4, get: 1, time: 636369282403838480, counter: 0
Current thread: 1, put: 3
Current thread: 4, get: 2, time: 636369282413840580, counter: 1
Current thread: 4, get: 3, time: 636369282423841740, counter: 2
Current thread: 4, get. Empty queue. Time: 4, 636369282433843170
WaitOne()
Current thread: 4, get. Empty queue. Time: 4, 636369282433844550
WaitOne()
Current thread: 1, put: 4
Current thread: 1, put: 5
Current thread: 4, get: 4, time: 636369282473841100, counter: 5
Current thread: 4, get: 5, time: 636369282483842040, counter: 6
Press any key...
Sample 3: Wait and Pulse
--------------------------
Current thread: 1, put: 1
Current thread: 1, put: 2
Current thread: 1, put: 3
Current thread: 5, get: 1, time: 636369278767371000, counter: 0
Current thread: 5, get: 2, time: 636369278777372110, counter: 1
Current thread: 5, get: 3, time: 636369278787373280, counter: 2
Current thread: 1, put: 4
Current thread: 1, put: 5
Current thread: 5, get: 4, time: 636369278797374490, counter: 3
Current thread: 5, get: 5, time: 636369278807375660, counter: 4
Press any key... |
|
Вопросы:
1 пример - почему очередь блокируется на всё время выполнения тела цикла, хотя, вроде бы получение данных только _queue.GetConsumingEnumerable()? Т.е. работает, как мне нужно, я просто не понимаю, почему?
| C# | 1
2
3
4
5
6
7
| foreach (string value in _queue.GetConsumingEnumerable())
{
// Выполняем задачу.
Console.WriteLine("Current thread: {0}, get: {1}, time: {2}",
Thread.CurrentThread.ManagedThreadId, value, DateTime.UtcNow.Ticks);
Thread.Sleep(1000);
} |
|
2 пример - не критично, но почему WaitOne() не сработал с первого раза и текст "Empty queue." напечатан дважды?
3 пример - насколько я понял у Альбахари, Pulse() пошлёт сигнал всем потокам, а у меня будет как минимум 3 пары Поставщик/получатель, у каждой пары будет свой поток для обработки, соответственно не нужно, чтобы поток обработки из второй пары перехватил Pulse от первой. При этом поток обработки в первой паре, как я понял может этот Pulse уже и не получить. Так ли это?
Кто использовал подобные конструкции, посоветуйте, пожалуйста, какой из этих методов лучше мне подходит?
У меня могут быть ситуации, когда за 1 секунду придут сотни, а может и тысячи строк данных от поставщика, а в другое время будут простои. Нужно, чтобы все данные были помещены в очередь, а потом обработаны, как можно меньше мешая классу-поставщику.
0
|