Created
February 15, 2017 23:02
-
-
Save JKamsker/5aaacff53049b81a83c9ed9574dea10a to your computer and use it in GitHub Desktop.
Async thread queue
This file contains hidden or 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
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