Skip to content

Instantly share code, notes, and snippets.

@Miragecore
Created March 25, 2020 02:13
Show Gist options
  • Save Miragecore/dddc44a125d35c00377b937a24dad44a to your computer and use it in GitHub Desktop.
Save Miragecore/dddc44a125d35c00377b937a24dad44a to your computer and use it in GitHub Desktop.
Task looping
//https://stackoverflow.com/questions/18490123/destructor-never-gets-called
public class Class : IDisposable
{
private Task task;
private CancellationTokenSource cts = new CancellationTokenSource();
AutoResetEvent arEvtProcRun = new AutoResetEvent(false);
Class()
{
task = new Task(Run, cts.Token, TaskCreationOptions.LongRunning);
task.Start();
}
public void Dispose()
{
cts.Cancel();
arEvtProcRun.Set();
}
private void Run()
{
while (!cts.Token.IsCancellationRequested)
{
arEvtProcRun.WaitOne();
if(cts.Token.IsCancellationRequested)
break;
// Your stuff goes here.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment