Run a method after async method completes

asked 2022-06-07T22:08:43.623+00:00
Timothy Fischer 116 Reputation points

I need to call a method after an async method completes -- it looks like this in my Windows Forms app:

    private async void btnGetOrganizations_Click(object sender, EventArgs e)
    {
        //need to check that the token is latest
        TokenIsValid();
        //need to call back to server
        WriteOrgsToRawJsonFile();
        tvwOrganizations.Nodes.Clear();

        List<IQOrganization> orgRawJson = await ReadOrgsFromRawJsonFile();
        PopulateOrganizationsAlphabetically(orgRawJson);

        //Reload the form
        this.OrganizationForm_Load(sender, e);
        MessageBox.Show("COMPLETE!");

    }

I need to have the form reload after getting the raw JSON from file. Is there an easy way to do this? I've already tried Task.Run() as well as .Wait() to no avial.

Thanks!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
6,922 questions
{count} votes

1 answer

Sort by: Most helpful
  1. answered 2022-06-08T00:59:42.353+00:00
    Karen Payne MVP 29,226 Reputation points Microsoft MVP

    One should never have to reload anything when coded properly.

    A do nothing example

    using System.Diagnostics;
    using System.Threading;
    
    namespace AsyncSimple.Classes
    {
        public class SomeService
        {
            public int Calculate()
            {
                static void BusyWait(int milliseconds)
                {
                    var sw = Stopwatch.StartNew();
    
                    while (sw.ElapsedMilliseconds < milliseconds)
                    {
                        Thread.SpinWait(1000);
                    }
                }
                // Tons of work to do in here!
                for (int index = 0; index < 10; index++)
                {
                    BusyWait(1000);
                }
    
                return 42;
            }
        }
    }
    

    Called and the form remains responsive, MessageBox is shown when done.

    private async void FakeWorkButton_Click(object sender, EventArgs e)
    {
        var service = new SomeService();
        await Task.Run(() => service.Calculate());
        MessageBox.Show("Done");
    }
    

    Back to your code, unsure how you are reading json but seems if from a file should something like this.

    public async Task SimpleReadAsync()
    {
        string filePath = "simple.txt";
        string text = await File.ReadAllTextAsync(filePath);
    }
    

    Add in deserializing and that's it.

    No comments