Is it possible to “await yield return DoSomethingAsync()”

前端 未结 9 932
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 14:08

Are regular iterator blocks (i.e. \"yield return\") incompatible with \"async\" and \"await\"?

This gives a good idea of what I\'m trying to do:

asyn         


        
9条回答
  •  独厮守ぢ
    2020-11-27 14:41

    This solution works as expected. Note the await Task.Run(() => enumerator.MoveNext()) part.

    using (var enumerator = myEnumerable.GetEnumerator())
    {
        while (true)
        {
            if (enumerator.Current != null)
            {
                //TODO: do something with enumerator.Current
            }
    
            var enumeratorClone = monitorsEnumerator;
            var hasNext = await Task.Run(() => enumeratorClone.MoveNext());
            if (!hasNext)
            {
                break;
            }
        }
    }
    

提交回复
热议问题