I am trying to execute an existing synchronous method asynchronously, however if the method is IEnumerable
, then it appears to skip over the method.
Here's a simplified version of what I'm trying to achieve.
public partial class MainWindow : Window
{
private IEnumerable<int> _Result;
public MainWindow()
{
InitializeComponent();
DoSomethingAmazing();
}
private async void DoSomethingAmazing()
{
_Result = await DoSomethingAsync();
}
private IEnumerable<int> DoSomething()
{
Debug.WriteLine("Doing something.");
//Do something crazy and yield return something useful.
yield return 10;
}
private async Task<IEnumerable<int>> DoSomethingAsync()
{
//Perform the DoSomething method asynchronously.
return await Task.Run(() => DoSomething());
}
}
Essentially, when then MainWindow
gets created, it will fire off an asynchronous method to populate the _Result
field.
Now DoSomething
never actually executes. The debug message never appears.
If I change IEnumerable
to List
, then all is well. The method gets executed and the result gets populated.
The main reason I want to use IEnumerable
is because I'd like to make use of yield return
, it's not exactly a requirement, but it's mainly just a preference. I came across this issue and I've been scratching my head ever since.