Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] User Defined Number of Listeners #51

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 29 additions & 16 deletions TaskClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Gofer.NET.Errors;
using Gofer.NET.Utils;
using Newtonsoft.Json;
using System.Linq;

namespace Gofer.NET
{
Expand All @@ -24,7 +25,7 @@ public class TaskClient

private Task TaskSchedulerThread { get; set; }

private Task TaskRunnerThread { get; set; }
private Task[] TaskRunnerThreads { get; set; }

private CancellationTokenSource ListenCancellationTokenSource { get; set; }

Expand All @@ -40,16 +41,22 @@ public TaskClient(

public async Task Listen()
{
Start();
await Listen(1);
}

public async Task Listen(int listenerThreads)
{
Start(listenerThreads);

var allList = TaskRunnerThreads.ToList();
allList.Add(TaskSchedulerThread);

await Task.WhenAll(new [] {
TaskRunnerThread,
TaskSchedulerThread});
await Task.WhenAll(allList);
}

public CancellationTokenSource Start()
public CancellationTokenSource Start(int listenerThreads)
{
if (TaskSchedulerThread != null || TaskRunnerThread != null)
if (TaskSchedulerThread != null || TaskRunnerThreads != null)
{
throw new Exception("This TaskClient is already listening.");
}
Expand All @@ -71,23 +78,29 @@ public CancellationTokenSource Start()
}
}, ListenCancellationTokenSource.Token);

TaskRunnerThread = Task.Run(async () => {
while (true)
{
if (token.IsCancellationRequested)
TaskRunnerThreads = new Task[listenerThreads];

for (int t = 0; t < listenerThreads; t++)
{
TaskRunnerThreads[t] = Task.Run(async () => {
while (true)
{
return;
}
if (token.IsCancellationRequested)
{
return;
}

await ExecuteQueuedTask();
}
}, ListenCancellationTokenSource.Token);
await ExecuteQueuedTask();
}
}, ListenCancellationTokenSource.Token);
}

return ListenCancellationTokenSource;
}

private async Task ExecuteQueuedTask()
{
Console.WriteLine("Dequing in thread {0}", Thread.CurrentThread.ManagedThreadId.ToString());
var (json, info) = await TaskQueue.SafeDequeue();
if (info != null)
{
Expand Down