Search code examples
c#multithreadingtask

Execute functions sequentially without blocking ui, in a loop


I need to execute 3 functions one after the other. One as to wait for the other to execute. That is also nested in a loop. How can I make the loop wait for the last task to finish before looping.

Here is what I have so far:

    private void Foo()
    {
        string[] files = GetFilesFromDir(@"C:\Bar\");
        if (files == null || files.Length < 0) { return; }

        for(int i = 0; i < files.Length; i++)
        {
            tbSked.Text = files[i];
            Task t1 = Task.Factory.StartNew(()=>LoadFile());
            t1.ContinueWith((a) => SQLUpdate());
            t1.ContinueWith((b) => RestartTimer());
        }
    }

Which works(does not freeze UI) but it goes through the loop as soon as executed.


Solution

  • Try something like this,

    private void Foo()
    {
        Task.Run(() => NormalMethod());
    }
    
    private void NormalMethod()
    {
        string[] files = GetFilesFromDir(@"C:\Bar\");
        if (files == null || files.Length < 0) { return; }
    
        for (int i = 0; i < files.Length; i++)
        {
            tbSked.Text = files[i];
            LoadFile();
            SQLUpdate();
            RestartTimer();
        }
    }