How to fix the output incomplete error

  • Thread starter Thread starter BenTam
  • Start date Start date
B

BenTam

Guest
I'm a beginner of C# programming. I copied the code from the book "Introduction to C# 8" to form a program. However my output (see screen capture below) are just 2 lines and is different from the output of the book.

Could anyone help me?

Thanks in advance!


Code and output from the book:

1616287.gif


My program:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Collections.Generic;

namespace AsyncTask2
{
public static class ConsoleExt
{
// Writes the message with timestamp and the thread Id.
public static void WriteLine(object message)
{
Console.WriteLine(
$"(Time: {DateTime.Now.ToShortTimeString()},Thread { Thread.CurrentThread.ManagedThreadId}): { message}");
}
// Writes the message with timestamp and the thread Id for the async methods.
public static async void WriteLineAsync(object message)
{
await Task.Run(() => Console.WriteLine(
$"(Time: {DateTime.Now.ToShortTimeString()},Thread { Thread.CurrentThread.ManagedThreadId}): { message}"));
}
// Loops and sums the provided argument (count)
}

class Program
{
static void Main()
{
Midd();
}

public static async void Midd()
{
const int count = 5;
ConsoleExt.WriteLine("SumFromOneToCountAsyncIEnumerable started!");
var scs = await SumFromOneToCountTaskIEnumerable(count);
ConsoleExt.WriteLine("SumFromOneToCountAsyncIEnumerable done!");
foreach (var sc in scs)
{
// This is not what we need; we become the result in one block!
ConsoleExt.WriteLine($"AsyncIEnumerable Result: {sc}");
}
ConsoleExt.WriteLine("SumFromOneToCountAsyncIEnumerable started!");
ConsoleExt.WriteLine("################################################");
ConsoleExt.WriteLine(Environment.NewLine);
}

static async Task<IEnumerable<int>> SumFromOneToCountTaskIEnumerable(int count)
{
{
ConsoleExt.WriteLine("SumFromOneToCountAsyncIEnumerable called!");
var collection = new Collection<int>();
var result = await Task.Run(() =>
{
var sum = 0;
for (var i = 0; i <= count; i++)
{
sum = sum + i;
collection.Add(sum);
}
return collection;
});

return result;
}
}

}
}


My output:

1616288.gif

Continue reading...
 
Back
Top