-5
\$\begingroup\$

Is there any cleaner way to implement the following?

await Task.Delay(100);
ExecutionProgress = .1;
await Task.Delay(100);
ExecutionProgress = .2;
await Task.Delay(100);
ExecutionProgress = .3;
await Task.Delay(100);
ExecutionProgress = .4;
await Task.Delay(100);
ExecutionProgress = .5;
await Task.Delay(100);
ExecutionProgress = .6;
await Task.Delay(100);
ExecutionProgress = .7;
await Task.Delay(100);
ExecutionProgress = .8;
await Task.Delay(100);
ExecutionProgress = .9;
await Task.Delay(100);
ExecutionProgress = 1;

For example, something like this?

await Task.Iterate(100, () => { ExecutionProgress += .1; }, 10);
\$\endgroup\$
  • \$\begingroup\$ await Task.Delay(100).ContinueWith(x=>ExecutionProgress += .1;);? You can extract progress update logic to separate function \$\endgroup\$ – Dmitry Pavliv May 21 '18 at 7:48
  • 1
    \$\begingroup\$ This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. Questions should include a description of what the code does \$\endgroup\$ – Dannnno May 21 '18 at 17:58
  • 1
    \$\begingroup\$ As has been discussed in chat, this is real code that is supposed to simulate a progressbar. \$\endgroup\$ – Simon Forsberg May 22 '18 at 12:56
1
\$\begingroup\$

Not sure it can be done in a one liner. A loop is better than repeating.

decimal  progress = 0; 
for(int i = 1; i <= 10; i++)
{
    Task.Delay(500);
    progress = i / 10;
}
\$\endgroup\$
  • \$\begingroup\$ I would prefer progress += 0.1 instead of doing division all the time. \$\endgroup\$ – Simon Forsberg May 22 '18 at 13:01
  • \$\begingroup\$ It can be one-lined, but IMO it's uglier and less readable than the equivalent for loop that you've used. But I do like the cleverness of it: Enumerable.Range(0, 10).ToList().ForEach(fe => await Task.Delay(100).ContinueWith(x => progress += 0.1;);) Also, I think you forgot to account for int division. \$\endgroup\$ – Flater May 25 '18 at 12:35
  • 1
    \$\begingroup\$ @SimonForsberg What I would prefer is to have the range on the bar 0 - 10 or 0 - 100 so can stay with int. \$\endgroup\$ – paparazzo May 31 '18 at 16:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.