Skip to content

Commit 2dbad4d

Browse files
committed
修改为异步方法
#5
1 parent f5ba8a0 commit 2dbad4d

File tree

1 file changed

+9
-10
lines changed

1 file changed

+9
-10
lines changed

AsyncWorkerCollection/AsyncTaskQueue_/AsyncTaskQueue.cs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
using System;
22
using System.Collections.Concurrent;
3-
using System.Threading;
3+
using System.Diagnostics;
44
using System.Threading.Tasks;
55

66
namespace dotnetCampus.Threading
@@ -15,9 +15,8 @@ public class AsyncTaskQueue : IDisposable
1515
/// </summary>
1616
public AsyncTaskQueue()
1717
{
18-
_autoResetEvent = new AutoResetEvent(false);
19-
_thread = new Thread(InternalRunning) { IsBackground = true };
20-
_thread.Start();
18+
_autoResetEvent = new AsyncAutoResetEvent(false);
19+
InternalRunning();
2120
}
2221

2322
#region 执行
@@ -102,14 +101,14 @@ private void AddPendingTaskToQueue(AwaitableTask task)
102101

103102
#region 内部运行
104103

105-
private void InternalRunning()
104+
private async void InternalRunning()
106105
{
107106
while (!_isDisposed)
108107
{
109108
if (_queue.Count == 0)
110109
{
111110
//等待后续任务
112-
_autoResetEvent.WaitOne();
111+
await _autoResetEvent.WaitOneAsync();
113112
}
114113

115114
while (TryGetNextTask(out var task))
@@ -151,6 +150,7 @@ private bool TryGetNextTask(out AwaitableTask task)
151150
return true;
152151
}
153152

153+
Debug.Assert(task != null);
154154
//并发操作,设置任务不可执行
155155
task.SetNotExecutable();
156156
}
@@ -182,10 +182,10 @@ private void Dispose(bool disposing)
182182
if (_isDisposed) return;
183183
if (disposing)
184184
{
185-
_autoResetEvent.Dispose();
185+
//_autoResetEvent.Dispose();
186186
}
187187

188-
_thread = null;
188+
_queue.Clear();
189189
_autoResetEvent = null;
190190
_isDisposed = true;
191191
}
@@ -206,8 +206,7 @@ private void Dispose(bool disposing)
206206

207207
private bool _isDisposed;
208208
private readonly ConcurrentQueue<AwaitableTask> _queue = new ConcurrentQueue<AwaitableTask>();
209-
private Thread _thread;
210-
private AutoResetEvent _autoResetEvent;
209+
private AsyncAutoResetEvent _autoResetEvent;
211210

212211
#endregion
213212
}

0 commit comments

Comments
 (0)