Run a method after async method completes

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

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.
11,298 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,551 Reputation points
    2022-06-08T00:59:42.353+00:00

    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.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.