My apologies, I am now out of the office so I don't have the exact code, but I would appreciate some advice on the following situation.
The situation
I have a winform application with one button. (Well actually several but it can be reduced to one). This button calls a series of asynchronous operations. Every time this button is called, the set of operations it calls is assigned a unique serial number. (this operations involved some HttpClient operation)
If I press the button again before the first set of operations is finished, an error is expected to be returned.
What I have
static int serialNumber=0;
private async void button_Clicked(object sender, EventArgs e)
{ int old= serialNumber;
serialNumber++;
//Do some stuff
//here and then
var result= await callFirstOperation(serialNumber);
if(!result)
{ serialNumber=old;
return;
}
//Do some more stuff
var result2= await callSecondOperation(serialNumber);
if(!result2)
{ serialNumber=old;
return;
}
//Some more stuff and async operations ....
Trace.WriteLine("Fiuuu... finished!");
}
As you can see when the button is pressed a serial operation is used for the rest of asyn operations, but if one of them fail, the number is back to the old value.
This would not be a problem if I press the button and wait for the completion of everything, But what happens if I press the button twice, the second time before the first set of operations is finished.
I thing serial number will be affected (by the second call) which will affect also the following operations of the first set.
What is the correct way to implement the objective?
Can static variables be used safely somehow with async functions?
EDIT: I thought that not resetting the serial number would help but think about this
First Time button-> Serial Number:1
(First time) Operation1(1)
(First time) Operation2(1)
Then second time button-> Serial Number :2
(Second time) Operation 1(2) returns error
(First time) Operation3(2)<---WAIT! this should be 1 not 2!
bool ButtonAlreadyPressedshould suffice. Make ittruein the beginning andfalseat the end. and perform the action onlyif(!ButtonAlreadyPressed){... do async stuff }