While this code is running i cant move or do anything in my UI:
var a = txtLot.Text;
var b = cmbMcu.SelectedItem.ToString();
var c = cmbLocn.SelectedItem.ToString();
var itm = Task<JDEItemLotAvailability>
.Factory.StartNew(() =>
{
btnCheck.BackColor = Color.Red;
var ret = Dal.GetLotAvailabilityF41021(a, b, c);
btnCheck.BackColor = Color.Transparent;
return ret;
}
);
lblDescriptionValue.Text = itm.Result.Description;
lblItemCodeValue.Text = itm.Result.Code;
lblQuantityValue.Text = itm.Result.AvailableQuantity.ToString();
I tried commenting on the call to the Dal method and putting thread.sleep(5000) instead but i still could’nt move the form.
edit: maybe i am using the wrong way to get back the result?
UPDATE:
After the first reply (John’s) i tried this:
var a = txtLot.Text;
var b = cmbMcu.SelectedItem.ToString();
var c = cmbLocn.SelectedItem.ToString();
var itm = Task<JDEItemLotAvailability>
.Factory.StartNew(() =>
{
btnCheck.BackColor = Color.Red;
var ret = Dal.GetLotAvailabilityF41021(a, b, c);
btnCheck.BackColor = Color.Transparent;
return ret;
}
).ContinueWith(itm =>
{
lblDescriptionValue.Text = itm.Result.Description;
lblItemCodeValue.Text = itm.Result.Code;
lblQuantityValue.Text = itm.Result.AvailableQuantity.ToString();
});
but of course i am messing ui again….The form freezing went away, but when task finished the exception occured
There are two problems here.
Firstly, your code is trying to access the UI thread from what is almost certainly a different thread (i.e. within the task, which will probably be executing in a thread-pool thread). You shouldn’t do that.
Secondly, you’re blocking the UI thread here:
Access to the
itm.Resultproperty will block until the task has completed. You don’t want to do that – this time in the UI thread – as that will freeze your UI, as you’ve observed.If you’re using C# 5 and .NET 4.5, you could try to use the new asynchrony features – that’s likely to make it much easier to do what you want.
If you can’t use .NET 4.5 (or the asynchrony targeting pack for .NET 4) you should use
Task.ContinueWithto tell theTaskwhat you want to do when it’s completed.EDIT: I suspect you want something like: