I have this:
private void BtnCheckClick(object sender, EventArgs e)
{
var a = txtLot.Text;
var b = cmbMcu.SelectedItem.ToString();
var c = cmbLocn.SelectedItem.ToString();
btnCheck.BackColor = Color.Red;
var task = Task.Factory.StartNew(() =>
Dal.GetLotAvailabilityF41021(a, b, c));
task.ContinueWith(t =>
{
btnCheck.BackColor = Color.Transparent;
lblDescriptionValue.Text = t.Result.Description;
lblItemCodeValue.Text = t.Result.Code;
lblQuantityValue.Text = t.Result.AvailableQuantity.ToString();
},TaskScheduler .FromCurrentSynchronizationContext() );
LotFocus(true);
}
and i followed J. Skeet’s advice to move into async,await in my .NET 4.0 app. I converted into this:
private async void BtnCheckClick(object sender, EventArgs e)
{
var a = txtLot.Text;
var b = cmbMcu.SelectedItem.ToString();
var c = cmbLocn.SelectedItem.ToString();
btnCheck.BackColor = Color.Red;
JDEItemLotAvailability itm = await Task.Factory.StartNew(() => Dal.GetLotAvailabilityF41021(a, b, c));
btnCheck.BackColor = Color.Transparent;
lblDescriptionValue.Text = itm.Description;
lblItemCodeValue.Text = itm.Code;
lblQuantityValue.Text = itm.AvailableQuantity.ToString();
LotFocus(true);
}
It works fine. What confuses me is that i could do it without using Task but just the method of my Dal. But that means that i must have modified my Dal method, which is something i dont want?
I would appreciate if someone would explain to me in “plain” words if what i did is optimal or not and why.
Thanks
P.s. My dal method
public bool CheckLotExistF41021(string _lot, string _mcu, string _locn)
{
using (OleDbConnection con = new OleDbConnection(this.conString))
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "select lilotn from proddta.f41021 " +
"where lilotn = ? and trim(limcu) = ? and lilocn= ?";
cmd.Parameters.AddWithValue("@lotn", _lot);
cmd.Parameters.AddWithValue("@mcu", _mcu);
cmd.Parameters.AddWithValue("@locn", _locn);
cmd.Connection = con;
con.Open();
OleDbDataReader rdr = cmd.ExecuteReader();
bool _retval = rdr.HasRows;
rdr.Close();
con.Close();
return _retval;
}
}
No, that’s not optimal at all. If you cannot change your DAL layer to be asynchronous you are not gaining much by using async/await. You are simply running your blocking DAL method inside a seprate background thread. If you want real gain, you should modify your DAL method to use asynchronous ADO.NET, a.k.a BeginXXX and EndXXX methods. Once you do that you will get real benefit from I/O Completion Ports. No threads will ever be jeopardized during the execution of the database call.
If you cannot modify your DAL method, whether you are using
JDEItemLotAvailability itm = await Task.Factory.StartNew(() => Dal.GetLotAvailabilityF41021(a, b, c));or manual thread creation, really, you gain nothing.