Skip to content

Instantly share code, notes, and snippets.

@Miragecore
Created March 25, 2020 02:13
Show Gist options
  • Select an option

  • Save Miragecore/dddc44a125d35c00377b937a24dad44a to your computer and use it in GitHub Desktop.

Select an option

Save Miragecore/dddc44a125d35c00377b937a24dad44a to your computer and use it in GitHub Desktop.

Revisions

  1. Miragecore created this gist Mar 25, 2020.
    31 changes: 31 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    //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.
    }
    }
    }