Skip to content

Instantly share code, notes, and snippets.

@JKamsker
Created February 15, 2017 23:02
Show Gist options
  • Save JKamsker/5aaacff53049b81a83c9ed9574dea10a to your computer and use it in GitHub Desktop.
Save JKamsker/5aaacff53049b81a83c9ed9574dea10a to your computer and use it in GitHub Desktop.
Async thread queue
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
namespace JFunctions.Async
{
public class ThreadQueue
{
private ConcurrentQueue<Action> processQueue = new ConcurrentQueue<Action>();
private AutoResetEvent waiter = new AutoResetEvent(false);
private Thread dispatcherThread;
public ThreadQueue()
{
dispatcherThread = new Thread(DispatchLoop);
dispatcherThread.Start();
}
private void DispatchLoop()
{
while (true)
{
waiter.WaitOne();
while (processQueue.Any())
{
if (processQueue.TryDequeue(out var func))
{
func();
}
}
}
}
public void EnqeueCall<T>(Func<T> call, Action<T> callback)
{
processQueue.Enqueue(() => callback(call()));
waiter.Set();
}
}
}
//EXAMPLE
// private void butLogin_Click(object sender, EventArgs e)
// {
// Settings.nq.EnqeueCall(() => Settings.requestExecutionPipe.doLogin("Darkie", "Darkie"), loginDoneCallback);
// Settings.nq.EnqeueCall(() => Settings.requestExecutionPipe.doLogin("Darkie", "Darkie"), (a) => { a.accessToken = "asd"; loginDoneCallback(a); });
// }
// public void loginDoneCallback(LoginRetDat data) {
// //do stuff
// if (InvokeRequired)
// {
// Invoke(new Action<LoginRetDat>(loginDoneCallback), new object[] { data });
// return;
// }
// this.Text = "hoho";
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment