Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delayed function calls

Tags:

function

c#

delay

Is there a nice simple method of delaying a function call whilst letting the thread continue executing?

e.g.

public void foo() {     // Do stuff!      // Delayed call to bar() after x number of ms      // Do more Stuff }  public void bar() {     // Only execute once foo has finished } 

I'm aware that this can be achieved by using a timer and event handlers, but I was wondering if there is a standard c# way to achieve this?

If anyone is curious, the reason that this is required is that foo() and bar() are in different (singleton) classes which my need to call each other in exceptional circumstances. The problem being that this is done at initialisation so foo needs to call bar which needs an instance of the foo class which is being created... hence the delayed call to bar() to ensure that foo is fully instanciated.. Reading this back almost smacks of bad design !

EDIT

I'll take the points about bad design under advisement! I've long thought that I might be able to improve the system, however, this nasty situation only occurs when an exception is thrown, at all other times the two singletons co-exist very nicely. I think that I'm not going to messaround with nasty async-patters, rather I'm going to refactor the initialisation of one of the classes.

like image 579
TK. Avatar asked Feb 13 '09 10:02

TK.


People also ask

How can we delay calling a function after 5 seconds?

Answer: To delay a function call, use setTimeout() function.

How do you call a function after a certain time?

You can use JavaScript Timing Events to call function after certain interval of time: This shows the alert box every 3 seconds: setInterval(function(){alert("Hello")},3000); You can use two method of time event in javascript.

What is JavaScript delay function?

setTimeout(function, milliseconds ) Executes a function, after waiting a specified number of milliseconds. setInterval(function, milliseconds ) Same as setTimeout(), but repeats the execution of the function continuously.


1 Answers

Thanks to modern C# 5/6 :)

public void foo() {     Task.Delay(1000).ContinueWith(t=> bar()); }  public void bar() {     // do stuff } 
like image 61
Korayem Avatar answered Sep 24 '22 07:09

Korayem