-
-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
04c9081
commit bd1f0e1
Showing
3 changed files
with
62 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Text; | ||
using System.Threading; | ||
using System.Collections.Concurrent; | ||
|
||
namespace RageCoop.Core | ||
{ | ||
public class Worker:IDisposable | ||
{ | ||
private SemaphoreSlim _semaphoreSlim; | ||
private Thread _workerThread; | ||
private bool _stopping=false; | ||
public string Name { get; set; } | ||
public bool IsBusy { get;private set; } | ||
internal Worker(int maxJobs = Int32.MaxValue,string name="Worker") | ||
{ | ||
Name = name; | ||
_semaphoreSlim = new SemaphoreSlim(maxJobs); | ||
_workerThread=new Thread(() => | ||
{ | ||
while (!_stopping) | ||
{ | ||
IsBusy=false; | ||
_semaphoreSlim.Wait(); | ||
if(Jobs.TryDequeue(out var job)) | ||
{ | ||
IsBusy=true; | ||
job.Invoke(); | ||
} | ||
else | ||
{ | ||
throw new InvalidOperationException("Hmm... that's unexpected."); | ||
} | ||
} | ||
IsBusy=false; | ||
}); | ||
_workerThread.Start(); | ||
} | ||
public void QueueWork(Action work) | ||
{ | ||
Jobs.Enqueue(work); | ||
_semaphoreSlim.Release(); | ||
} | ||
public void Stop() | ||
{ | ||
_stopping=true; | ||
if (_workerThread.IsAlive) | ||
{ | ||
_workerThread.Join(); | ||
} | ||
} | ||
public void Dispose() | ||
{ | ||
Stop(); | ||
_semaphoreSlim.Dispose(); | ||
} | ||
private ConcurrentQueue<Action> Jobs=new ConcurrentQueue<Action>(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters