Typically, you do this by executing a thread that is a delegate of the method on the object, with this object displaying the Cancel property, and a lengthy operation that passes this property periodically to tru to determine whether to exit.
eg
public class MyLongTunningTask { public MyLongRunninTask() {} public volatile bool Cancel {get; set; } public void ExecuteLongRunningTask() { while(!this.Cancel) {
Then in another place:
var longRunning = new MyLongTunningTask(); Thread myThread = new Thread(new ThreadStart(longRunning.ExecuteLongRunningTask)); myThread.Start(); // somewhere else longRunning.Cancel = true;
source share