I want to cancel button click event while executing any heavy method in C#. Lets say there is following method and event:
private void Submit()
{
//This method requires 5 seconds and it is blocking method
}
private void button_Click(object sender, EventArgs e)
{
//Some code here
}
When I click on button while executing Submit method, the button click event does not fire, instead of it fires after completed the execution of Submit method.
I want to cancel this event when clicked while executing the Submit method. I can not disable this button as my application contains many of such buttons. I also want to prevent all events to be fired that is initiated during execution of Submit method if possible and allow all events to be fired after execution of Submit method.
Pls suggest any solution or workaround to achieve the about task.
If you start a new task using async, you will be able to call the cancel method whilst executing the Submit.
private async Task Submit()
{
await Task.Factory.StartNew(() =>
{
// Blocking code, network requests...
});
}
Have a look at https://msdn.microsoft.com/en-us/library/mt674882.aspx for await async reference, and also Channel 5 has some great videos about it https://channel9.msdn.com/Series/Three-Essential-Tips-for-Async
If you want to stop "Submit" whenever you trigger "Cancel", I would recommend using a CancellationEventSource to cancel the task, have a look:
using System.Threading.Tasks;
private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private async Task Submit()
{
var cancellationToken = this.cancellationTokenSource.Token;
await Task.Factory.StartNew(() =>
{
cancellationToken .ThrowIfCancellationRequested();
// Blocking code, network requests...
}, this.cancellationTokenSource.Token);
}
private void button_Click(object sender, EventArgs e)
{
this.cancellationTokenSource.Cancel();
}
Have a look at this msdn article on CancellationTokenSource and Task https://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx
Edit 1:
I don't want to stop the Submit() any more. I want to cancel the event during execution of Submit() and allow event to be fired after completion of the Submit()
Create a Task and await for it to finish:
private Task submitTask;
private void Submit()
{
this.submitTask = Task.Factory.StartNew(() =>
{
// Some Code
}
}
private async void button_Click(object sender, EventArgs e)
{
// Awaiting will prevent blocking your UI
await this.submitTask;
// Some Code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With