Delayed function calls

后端 未结 12 1323
星月不相逢
星月不相逢 2020-11-30 22:07

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

e.g.

public void foo()
{
    // Do stuff!

           


        
12条回答
  •  星月不相逢
    2020-11-30 22:31

    It's indeed a very bad design, let alone singleton by itself is bad design.

    However, if you really do need to delay execution, here's what you may do:

    BackgroundWorker barInvoker = new BackgroundWorker();
    barInvoker.DoWork += delegate
        {
            Thread.Sleep(TimeSpan.FromSeconds(1));
            bar();
        };
    barInvoker.RunWorkerAsync();
    

    This will, however, invoke bar() on a separate thread. If you need to call bar() in the original thread you might need to move bar() invocation to RunWorkerCompleted handler or do a bit of hacking with SynchronizationContext.

提交回复
热议问题