Skip to content

Instantly share code, notes, and snippets.

@Rohansi
Last active August 29, 2015 13:58
Show Gist options
  • Save Rohansi/9985926 to your computer and use it in GitHub Desktop.
Save Rohansi/9985926 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace taskschedule
{
class Program
{
static void Main(string[] args)
{
var scheduler = new Scheduler();
var taskFactory = new TaskFactory(scheduler);
var completionSources = new List<TaskCompletionSource<ConsoleKeyInfo>>();
Func<Task<ConsoleKeyInfo>> getKey = () =>
{
var completion = new TaskCompletionSource<ConsoleKeyInfo>();
completionSources.Add(completion);
return completion.Task;
};
taskFactory.StartNew(async () =>
{
Console.WriteLine("3");
await Task.Delay(1000);
Console.WriteLine("2");
await Task.Delay(1000);
Console.WriteLine("1");
while (true)
{
var key = await getKey();
Console.WriteLine("pressed: {0}", key.KeyChar);
}
});
taskFactory.StartNew(async () =>
{
int i = 0;
while (true)
{
Console.WriteLine("i: {0}", i++);
await Task.Delay(1000);
}
});
taskFactory.StartNew(async () =>
{
while (true)
{
var client = new WebClient();
var data = await client.DownloadDataTaskAsync(new Uri("http://fpp.literallybrian.com/"));
Console.WriteLine("rohbot is {0} bytes", data.Length);
await Task.Delay(250);
}
});
while (true)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
foreach (var completion in completionSources)
{
completion.SetResult(key);
}
completionSources.Clear();
}
scheduler.Run();
Thread.Sleep(1);
}
}
}
public class Scheduler : TaskScheduler
{
private List<Task> _tasks;
public Scheduler()
{
_tasks = new List<Task>();
}
public void Run()
{
lock (_tasks)
{
foreach (var task in _tasks.ToArray())
{
if (TryExecuteTask(task))
_tasks.Remove(task);
}
}
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return _tasks;
}
protected override void QueueTask(Task task)
{
lock (_tasks)
{
_tasks.Add(task);
}
}
protected override bool TryDequeue(Task task)
{
lock (_tasks)
{
return _tasks.Remove(task);
}
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment