-1

I have a loop I made like

        for(DateTime later = DateTime.Now.AddSeconds(5); DateTime.Now < later; Thread.Sleep(500))
        {

            // ... stuff
        }

and I'm wondering whether there is an easy way to convert that to a non-blocking way of doing stuff.

Trump2016
  • 21
  • 1
  • 2
  • 1
    using a `for` loop for this is very werid. Make it a `while` loop and it will be much more obvious how to change it to asnyc. Also, the "best way" to make it async depends on what you are doing with `// ... stuff`, do you need to interact with the UI? do you need to do more things after the `for` loop? – Scott Chamberlain Aug 26 '16 at 21:49

2 Answers2

0

My favorite way of doing so is to use a backgroundworker class and insert your function into its RunWorkerAsynch/DoWork method. Good examples are mentioned here and here.

alternatively you can run a separate thread. There are tons of articles about multi-threading in c#.

Community
  • 1
  • 1
AleX_
  • 508
  • 1
  • 6
  • 20
0

Add a thread object and put the blocking loop inside it, like this:

    public static void Start()
    {
        for(DateTime later = DateTime.Now.AddSeconds(5); DateTime.Now < later; Thread.Sleep(500))
        {
            Console.WriteLine("Other Thread: " + DateTime.Now.ToLongTimeString());
        }
    }

    public static void Main(string[] args)
    {
        Thread thread = new Thread(Start);
        thread.Start(); 
    }

See https://msdn.microsoft.com/en-us/library/system.threading.threadstart(v=vs.110).aspx for more info.

Here's a little example I made... http://rextester.com/QWMG44444 enjoy!

Richard Bamford
  • 1,835
  • 3
  • 15
  • 19