I have a strange problem with
FileStream.ReadAsync()
. I call a function that performs an asynchronous read from a stream from my main application
OnStartup()
. When I read asynchronously, the application doesn't ever display its main window. If I simply change the read to a synchronous version, the application starts up.
This is my
OnStartup()
override:
protected override async void OnStartup( StartupEventArgs e )
{
base.OnStartup( e );
Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
LogsEmailer logsEmailer = new LogsEmailer();
string testString = await logsEmailer.TestReadFileAsync( Path.Combine( logsFolder, "TestFile.txt" ) );
StartupUri = new Uri( "./View/MainWindow.xaml", UriKind.Relative );
}
The application never starts with this function:
public async Task<string> TestReadFileAsync( string filePath )
{
using( FileStream sourceStream = File.OpenRead( filePath ) )
{
byte[] copyBuffer = new byte[ 4096 ];
bool doneCopying = false;
while( !doneCopying )
{
int numSourceBytes = await sourceStream.ReadAsync( copyBuffer, 0, copyBuffer.Length );
if( numSourceBytes == 0 )
doneCopying = true;
}
}
return "test string";
}
But it does start with this:
public async Task<string> TestReadFileAsync( string filePath )
{
using( FileStream sourceStream = File.OpenRead( filePath ) )
{
byte[] copyBuffer = new byte[ 4096 ];
bool doneCopying = false;
while( !doneCopying )
{
int numSourceBytes = sourceStream.Read( copyBuffer, 0, copyBuffer.Length );
if( numSourceBytes == 0 )
doneCopying = true;
}
}
return "test string";
}
Obviously, I do get a warning with the second piece of code that says it will complete synchronously. And when I say that the second version works, I mean only that it allows the application to start; I can't use it because the operation I am trying to perform takes too long to be done synchronously in
OnStartup()
.
I guess I am missing something silly here. Can anyone tell me what?
What I have tried:
I I mentioned above, I have tried removing the async from the stream-read and the application starts okay.
I have just discovered that if I change my
OnStartup()
override to be as follows then the application starts up okay.
protected override async void OnStartup( StartupEventArgs e )
{
base.OnStartup( e );
Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
StartupUri = new Uri( "./View/MainWindow.xaml", UriKind.Relative );
LogsEmailer logsEmailer = new LogsEmailer();
string testString = await logEmailer.TestReadFileAsync( Path.Combine( logsFolder, "TestFile.txt" ) );
}