Search code examples
c#wpfmultithreadinguser-interfaceftp

Why doesn't it update the ui then run the code wpf


I have this code where I upload some streams to an ftp server. But before that I want to make the spinnerContainer visible. But if I call the method it freezez (It started uploading) and only show the container after it's finished.

spinnerContainer.Visibility = Visibility.Visible;

client.Connect();
client.EmptyDirectory(Id);
client.SetWorkingDirectory(Id);
for (int i = 0; i < streams.Count; i++)
{
    client.UploadStream(streams[i], i.ToString());
}
client.Disconnect();

I want to run the spinnerContainer.Visibility = Visibility.Visible; first then the rest. How can I achieve this?


Solution

  • Your code runs on the UI thread, so until the UI method completes execution, the UI thread will be blocked and the GUI will not update.
    Use asynchrony:

    private async Task SomeMethod()
    {
        spinnerContainer.Visibility = Visibility.Visible;
    
        await Task.Run(() =>
        {
            client.Connect();
            client.EmptyDirectory(Id);
            client.SetWorkingDirectory(Id);
            for (int i = 0; i < streams.Count; i++)
            {
                client.UploadStream(streams[i], i.ToString());
            }
    
            client.Disconnect();
        });
    
    }
    

    The call of the method has to be awaited:

    await SomeMethod();
    

    In case you are calling it from an event handler, the handler method must be declared async void.