//Chaining tasks private async Task ChainExecuteOnly(int iQuery, List <string> lstQueries) { //Build tasks based on the list of queries passed in and execute all async. CDatabase database = new CDatabase(); //Build task list List <Task <int> > lstTasks = new List <Task <int> >(); lstQueries.ForEach(delegate(string sQuery) { Task <int> ExecuteTask = database.ExecuteAsync(txtConnectionString.Text, sQuery); lstTasks.Add(ExecuteTask); }); //Convert to array and run Task <int>[] arrTasks = lstTasks.ToArray(); await Task.WhenAll(arrTasks); //Get results int iRowsAffected = 0; lstTasks.ForEach(delegate(Task <int> tTask) { iRowsAffected += tTask.Result; }); //Log results AddLogItem(String.Format("{0} Row(s) Updated", iRowsAffected)); }
//Execute only private async Task ExecuteOnly(int iQuery) { CDatabase database = new CDatabase(); try { //Using task function to run the command asynchronously and get the number of rows affected. int iResults = await database.ExecuteAsync(txtConnectionString.Text, txtSQLQuery.Text); //Log the rows affected. if (iResults < 0) { AddLogItem("No Rows Updated"); } else { AddLogItem(String.Format("{0} Row(s) Updated", iResults)); } } catch (Exception ex) { //In this case our task function is set to pass the error through to the caller, log error to list. AddLogItem("Execute Only Error: " + ex.Message); } }
//Results to text private async Task ResultsToText(int iQuery) { CDatabase database = new CDatabase(); //Using task function to get results to custom class and pass through to separate method using "ContinueWith" //Sidenote 1: I use "this.Invoke" as the PopulateTextResults needs to add controls to form. //Sidenote 2: The error is caught by the function and passed via the custom class object. await database.GetTextDataToCustomClassAsync(txtConnectionString.Text, txtSQLQuery.Text).ContinueWith(t => this.Invoke((Action)(() => { PopulateTextResults(iQuery, t.Result); }))); }
//Results to grid private async Task ResultsToGrid(int iQuery) { CDatabase database = new CDatabase(); try { //Using task function to get dataset asynchronously. DataSet results = await database.GetDataSetAsync(txtConnectionString.Text, txtSQLQuery.Text); //Now that we have our data populate to new tab. PopulateGridResults(iQuery, results.Tables[0]); } catch (SqlException sqlError) { //In this case our task function is set to pass the error through to the caller, log error to list. AddLogItem("ResultsToTable Error: " + sqlError.Message); } }