How to stop the flow?

Try to stop the flow:
wait.Stop = delegate ()
{
myThread.Abort();
};
 myThread.Start();

In the form of:
public Action Worker { get; }
 public Action Stop { get; set; }
 private Thread thread;
 public FormWait(Action worker)
{
InitializeComponent();
 if (worker == null)
 throw new ArgumentNullException();
 Worker = worker;
}
 protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
 //thread = new Thread(new ThreadStart(delegate ()
//{
 // Worker();
//}));
//thread.Start();
 Task.Factory.StartNew(Worker).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
}

 private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("Stop");
Stop();
 }


But why it doesn't work out how to stop the flow?
March 19th 20 at 08:55
1 answer
March 19th 20 at 08:57
To stop the flow need not kill him, and stop, preferably on the inside. And that it could be done, you need to pass the token inside the stop. The shutdown does nothing, but it is used within the body of the thread to cancel or abort. This token will be passed to Worker, which you will need to check for stop using cancellationToken.IsCancellationRequested. If the worker loop is used, then you can check in each iteration.

var formWait = new FormWait(cancellationToken => 
{
 foreach(var item in _items)
{
 if (cancellationToken.IsCancellationRequested)
{
return;
}
item.DoWork();
}
});


wait.Stop = delegate ()
{
 var source = _tokenSource;
 if (source != null)
{
source.Cancel();
source.Dispose();
 _tokenSource = null;
}
};
myThread.Start();

In the form of:
 public Action<CancellationToken> Worker { get; } // add a reference to the token stop
 public Action Stop { get; set; }
 private CancellationTokenSource _tokenSource;
 public FormWait(Action<CancellationToken> worker)
{
InitializeComponent();
 if (worker == null)
 throw new ArgumentNullException();
 Worker = worker;
}
 protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_tokenSource?.Dispose();
 _tokenSource = new CancellationTokenSource();
 var cancellationToken = = _tokenSource.Token;
 Task.Factory.StartNew(() => Worker(cancellationToken ))
 .ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
}

 private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("Stop");
Stop();
 }


It's probably a good task to do with the return result, for example
public Func<CancellationToken, bool> Worker { get; }

Task.Factory.StartNew<bool>(() => Worker(cancellationToken))
.ContinueWith(t => { if (t.Result) this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());

Find more questions by tags C#