c#


Unable to cancel Async/Awaiting call on button click


I am unable to cancel async/await call on cancel button click. I want to cancel query if it will take long time to load data in grid. I am new to use async/await method and referred many examples, but unable workout if. Pleas have look on my below code and Please help. thanks
namespace MyFirstAsync
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
CancellationTokenSource cts ;
private async void btnExecute_Click(object sender, EventArgs e)
{
cts = new CancellationTokenSource();
try
{
string connectionString = "Data Source=G50-80;Initial Catalog=HPSF_Compdb;User ID=sa;Password=sql#2012";
string sqlQuery = "select top 900000 * from requestevent.result";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
await conn.OpenAsync(cts.Token);
SqlDataReader reader = await cmd.ExecuteReaderAsync(cts.Token);
DataTable dt = new DataTable();
//cts.Cancel();
await Task.Run(() => dt.Load(reader), cts.Token);
gvData.Invoke(new gvDelegate(UpdateDataToGrid), new object[] { dt });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public delegate void gvDelegate(DataTable dt);
public void UpdateDataToGrid(DataTable dt)
{
gvData.DataSource = dt;
}
private void btncancel_Click(object sender, EventArgs e)
{
cts.Cancel();
}
}
}
The problem is with this line of code:
await Task.Run(() => dt.Load(reader), cts.Token);
Contrary to what you may expect, the CancellationToken passed to Task.Run only cancels the starting of that task, not the task itself. In other words, once Load has started, it can't be canceled.
Ideally, you should be using something other than DataTables in modern code; other database APIs have been updated to support cancellation. If this is not possible, then you can use the CancellationTokenRegistration as in your answer. However, you should not use Result - use await instead:
using (CancellationTokenRegistration ctr = cts.Token.Register(() => cmd.Cancel()))
using (var reader = await cmd.ExecuteReaderAsync(cts.Token))
dt.Load(reader);
I found solution of above issue, just changed the way of data loading to datatable. Pls refer commented old code replaced with new code and it is working excellent as expected. New code I just copy and paste and still I don't know how to describe new code the way of it working as I am new on this. But it is working for me. Please explain someone if you differentiate between both.
using (CancellationTokenRegistration ctr = cts.Token.Register(() => cmd.Cancel()))
{
using (var reader = cmd.ExecuteReaderAsync(cts.Token))
{
dt.Load(reader.Result);
}
}
//SqlDataReader reader = await cmd.ExecuteReaderAsync(cts.Token);
//DataTable dt = new DataTable();
//await Task.Run(() => dt.Load(reader), cts.Token);

Related Links

Linq To Sql Query Between CommaSeprated column and list?
C# code to pass value of textbox created using for loop to another page
Group nested list with linq
How to update control inside ListBox item
Structuring XDocument to properly format Tags
Find Item in List when particular financial value is reached
how to sleep child form without sleeping parent or other child forms
Is a pipeline with a changing data type architecturally sound?
XPathNavigator with xpath gives wrong node back
ASP.net Call function in Default.aspx.cs from the Site.Master.cs class
Differences Between EntityTypeConfiguration & EntityConfiguration
Re-load Unloaded Projects in EnvDTE
Allocation Formula [closed]
GetHashCode and Buckets
Wait on a process in a task
Check if decimal value is null

Categories

HOME
google-cloud-pubsub
teradata
ssh
cluster-analysis
process
skypedeveloper
x86-64
ms-application-insights
sugarcrm
schema
python-3.4
promotions
spring-data-solr
camunda
udeploy
computation-theory
android-wifi
angular2-pipe
procedural-generation
bootstrap-accordion
apdu
datastax-enterprise
proof-general
custom-fields
pushpad
openoffice-impress
undo
boost-log
key-bindings
oracle-nosql
node-soap
geocomplete
hippocms
multi-user
rythm
const
mybatis-generator
lfe
google-cloud-powershell
result
android-doze-and-standby
spring-webflow-2
google-chrome-storage
react.rb
wink
printer-control-language
scrollmagic
breadcrumbs
class-design
foreground
queuing
sbt-proguard
shtml
aws-kms
razorengine
periodic-processing
hana-sql-script
containstable
cascading
android-facebook
transport
tokudb
data-representation
mergecursor
beagleboard
conkeror
attiny
xmla
information-hiding
go-gin
selenium-grid2
livescript
twitter-finagle
hotlinking
email-headers
db2-connect
nativequery
google-oauth-java-client
sygic
grape-api
tlbimp
record-locking
maven-webstart-plugin
jython-2.5
pyxplot
wpd
panelgrid
symbian3
http-compression
vline
metapost
configurationsection
socketasynceventargs
project-files
automapper-2
wdm
httppostedfilebase
vectorwise
jqtransform
webdb
versions
dgml

Resources

Encrypt Message