0

In my program I am writing a Resource File into some Location the user selects. For that I am using GetManifestResourceStream. Everything worked fine.

Next I wanted to make my writing operation not-blocking the UI. So I changed the code using async await. Unfortunately GetManifestRresourceStream is returning null now. Changing back without using async await everything works fine again.

What am I doing wrong and how can I solve it so that I am able to copy the file and the UI is not blocked.

This Is how it works without async/await (Please dont be confused by the Method Names)

 private void InstallButton_Click(object sender, RoutedEventArgs e)
        {
            InstallProgrammAsyc();
        }

private void InstallProgrammAsyc()
        {
            try
            {
                FinalMessage = "";
                PreInstallationBlock.Visibility = Visibility.Collapsed;
                DuringInstallationBlock.Visibility = Visibility.Visible;
                CopyFileToDestinationAsync("MyNameSpace", InstallPath, "Resources", "some.exe");
                PrepareProgrammForFinish();
            }
            catch (Exception ex)
            {
                DuringInstallationBlock.Visibility = Visibility.Collapsed;
                AfterInstallationBlock.Visibility = Visibility.Visible;
                FinalMessage = $"Unexpected Error occured. Please try again. {ex.Message}";
            }
        }

 private void CopyFileToDestinationAsync(string nameSpace,string outDirectory, string internalPath, string resourceName)
        {
            Assembly assembly = Assembly.GetCallingAssembly();
            using (Stream stream = assembly.GetManifestResourceStream(nameSpace + "." + (internalPath == "" ? "" : internalPath + ".") + resourceName))
            {
                using( BinaryReader br = new BinaryReader(stream))
                {
                    using(FileStream fs = new FileStream(outDirectory + "\\" + resourceName, FileMode.Create))
                    {
                        using (BinaryWriter bw = new BinaryWriter(fs))
                        {
                            // await Task.Run( ()=> bw.Write(br.ReadBytes((int)stream.Length)));
                            bw.Write(br.ReadBytes((int)stream.Length));
                        }
                    }
                }
            }
            Thread.Sleep(2000);
            //For User Friendliness wait 2 seconds to finish
           // await Task.Run(() => Thread.Sleep(2000));
        }


----------


And this Is how I tried it with async/await



        private async Task CopyFileToDestinationAsync(string nameSpace,string outDirectory, string internalPath, string resourceName)
        {
            Assembly assembly = Assembly.GetCallingAssembly();
            using (Stream stream = assembly.GetManifestResourceStream(nameSpace + "." + (internalPath == "" ? "" : internalPath + ".") + resourceName))
            {
                using( BinaryReader br = new BinaryReader(stream))
                {
                    using(FileStream fs = new FileStream(outDirectory + "\\" + resourceName, FileMode.Create))
                    {
                        using (BinaryWriter bw = new BinaryWriter(fs))
                        {
                             await Task.Run( ()=> bw.Write(br.ReadBytes((int)stream.Length)));
                          //  bw.Write(br.ReadBytes((int)stream.Length));
                        }
                    }
                }
            }
            //Thread.Sleep(2000);
            //For User Friendliness wait 2 seconds to finish
            await Task.Run(() => Thread.Sleep(2000));
        }


        private void FinishButton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Application.Current.Shutdown();
        }

        private async void InstallProgrammAsyc()
        {
            try
            {
                FinalMessage = "";
                PreInstallationBlock.Visibility = Visibility.Collapsed;
                DuringInstallationBlock.Visibility = Visibility.Visible;
                await CopyFileToDestinationAsync("MyNameSpace", InstallPath, "Resources", "some.exe");
                PrepareProgrammForFinish();
            }
            catch (Exception ex)
            {
                DuringInstallationBlock.Visibility = Visibility.Collapsed;
                AfterInstallationBlock.Visibility = Visibility.Visible;
                FinalMessage = $"Unexpected Error occured. Please try again. {ex.Message}";
            }
        }

        private void InstallButton_Click(object sender, RoutedEventArgs e)
        {
            InstallProgrammAsyc();
        }
3
  • I solved the problem by calling the GetManifestResourceStream Function outside and passing the Stream as a Parameter to the async Function. However I would really like to know why it is not functioning the way I tried before.
    – Kerem
    Commented Mar 28, 2020 at 15:47
  • 1
    It's very likely that Assembly.GetCallingAssembly is not returning the assembly you're expecting Commented Mar 29, 2020 at 9:34
  • Yes maybe. I also tried to use the other ones. But that didn't help either.
    – Kerem
    Commented Mar 29, 2020 at 14:43

1 Answer 1

2

That's an interesting edge case, due to how async works.

Let's take those test methods:

private void Button_Click(object sender, RoutedEventArgs e)
{
    ShowAssembly();
    ShowAssemblyAsync();
}

private void ShowAssembly()
{
    Assembly assembly = Assembly.GetCallingAssembly();

    MessageBox.Show(assembly.FullName);
}

private async void ShowAssemblyAsync()
{
    Assembly assembly = Assembly.GetCallingAssembly();

    MessageBox.Show(assembly.FullName);
}

In ShowAssembly, it'll display the name of your program's main assembly. In ShowAssemblyAsync, it'll display "mscorlib". What's going on?

If you put a breakpoint in ShowAssembly and ShowAssemblyAsync in Visual Studio, you'll get the following callstacks:

DesktopClient.exe!DesktopClient.MainWindow.ShowAssembly() Line 119  C#
DesktopClient.exe!DesktopClient.MainWindow.Button_Click(object sender, System.Windows.RoutedEventArgs e) Line 109   C#
DesktopClient.exe!DesktopClient.MainWindow.ShowAssemblyAsync() Line 128 C#
DesktopClient.exe!DesktopClient.MainWindow.Button_Click(object sender, System.Windows.RoutedEventArgs e) Line 110   C#

Nothing fishy there. However, Visual Studio is lying to you. If I instead use a lower level debugger (in this case, WinDbg), I get the following callstacks:

00efe58c 07cf423b DesktopClient.MainWindow.ShowAssembly() 
00efe5a8 07cf41dc DesktopClient.MainWindow.Button_Click(System.Object, System.Windows.RoutedEventArgs) 
00efe4d8 07cf43c6 DesktopClient.MainWindow+d__10.MoveNext() 
00efe51c 5ddaa48d System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[[System.__Canon, mscorlib]](System.__Canon ByRef)
00efe574 07cf4317 DesktopClient.MainWindow.ShowAssemblyAsync()
00efe5a8 07cf41e6 DesktopClient.MainWindow.ButtonPlus_Click(System.Object, System.Windows.RoutedEventArgs) 

You can see that the callstack from ShowAssemblyAsync has been completely changed after applying the async keyword (Visual Studio is hiding that to make debugging easier). One consequence is that the method is now called by System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start, and that's why we get "mscorlib" when retrieving the calling assembly.

As a fix, you can either use Assembly.GetExecutingAssembly (assuming your CopyFileToDestinationAsync method is located in the right assembly) or target the assembly explicitly: typeof(MainWindow).Assembly. Or, like you did, just retrieve the stream before calling the method.

Yet another way is to introduce an extra non-async method just to retrieve the assembly before calling the real async implementation:

private Task CopyFileToDestinationAsync(string nameSpace,string outDirectory, string internalPath, string resourceName)
{
    Assembly assembly = Assembly.GetCallingAssembly();

    return CopyFileToDestinationAsync(assembly, nameSpace, outDirectory, internalPath, resourceName);
}

private async Task CopyFileToDestinationAsync(Assembly assembly string nameSpace,string outDirectory, string internalPath, string resourceName)
{
    using (Stream stream = assembly.GetManifestResourceStream(nameSpace + "." + (internalPath == "" ? "" : internalPath + ".") + resourceName))
    {
        // ...
    }
}
1
  • Thank you very much. That was really helpful for better understanding.
    – Kerem
    Commented Mar 29, 2020 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.