Need Help in Compiling C# Simple Multithreading Program

SamUSA

New member
Joined
Dec 20, 2022
Messages
2
Programming Experience
10+
Hello,
Regularly, I develop C++ software using Visual Studio 2022.

I never programed C#.

Today, I bought two Kindle app books on Amazon.com in the United States.
1. Concurrency in C# cookbook by Stephen Cleary
2. Microsoft Visual C# Step by Step 10th Edition by John Sharp

My goal is to compare C# multithreading methods/algorithms and see if I can use C# techniques in my C++ programs?

My question is how to compile and run the multithreading C# programs from the above Concurrency in C# Cook Book using VS2022?

I have created in VS2022, C# Windows console application project, built and ran the following program of chapter 1 of above Step by Step book.


Program.cs:
using System;

namespace HelloWorld2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

I need detailed steps for comping C# Concurrency programs from Chapter 1 of above Cook Book, please ?

Thanks and best regards,


ch01.cs:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;

class ch01_01
{
  async Task DoSomethingAsync()
  {
    int value = 13;

    // Asynchronously wait 1 second.
    await Task.Delay(TimeSpan.FromSeconds(1));

    value *= 2;

    // Asynchronously wait 1 second.
    await Task.Delay(TimeSpan.FromSeconds(1));

    Trace.WriteLine(value);
  }
}

abstract class ch01_02
{
  async Task DoSomethingAsync()
  {
    int value = 13;

    // Asynchronously wait 1 second.
    await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);

    value *= 2;

    // Asynchronously wait 1 second.
    await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);

    Trace.WriteLine(value);
  }
}

abstract class ch01_03
{
  public abstract Task PossibleExceptionAsync();
  public abstract void LogException(Exception ex);

  async Task TrySomethingAsync()
  {
    try
    {
      await PossibleExceptionAsync();
    }
    catch (NotSupportedException ex)
    {
      LogException(ex);
      throw;
    }
  }
}

abstract class ch01_04
{
  public abstract Task PossibleExceptionAsync();
  public abstract void LogException(Exception ex);

  async Task TrySomethingAsync()
  {
    // The exception will end up on the Task, not thrown directly.
    Task task = PossibleExceptionAsync();

    try
    {
      // The Task's exception will be raised here, at the await.
      await task;
    }
    catch (NotSupportedException ex)
    {
      LogException(ex);
      throw;
    }
  }
}

class ch01_05
{
  async Task WaitAsync()
  {
    // This await will capture the current context ...
    await Task.Delay(TimeSpan.FromSeconds(1));
    // ... and will attempt to resume the method here in that context.
  }

  void Deadlock()
  {
    // Start the delay.
    Task task = WaitAsync();

    // Synchronously block, waiting for the async method to complete.
    task.Wait();
  }
}

class ch01_06
{
  abstract class Matrix
  {
    public abstract void Rotate(float degrees);
  }

  void RotateMatrices(IEnumerable<Matrix> matrices, float degrees)
  {
    Parallel.ForEach(matrices, matrix => matrix.Rotate(degrees));
  }
}

abstract class ch01_07
{
  public abstract bool IsPrime(int value);

  IEnumerable<bool> PrimalityTest(IEnumerable<int> values)
  {
    return values.AsParallel().Select(value => IsPrime(value));
  }
}

class ch01_08
{
  void ProcessArray(double[] array)
  {
    Parallel.Invoke(
        () => ProcessPartialArray(array, 0, array.Length / 2),
        () => ProcessPartialArray(array, array.Length / 2, array.Length)
    );
  }

  void ProcessPartialArray(double[] array, int begin, int end)
  {
    // CPU-intensive processing...
  }
}

class ch01_09
{
  void Test()
  {
    try
    {
      Parallel.Invoke(() => { throw new Exception(); },
          () => { throw new Exception(); });
    }
    catch (AggregateException ex)
    {
      ex.Handle(exception =>
      {
        Trace.WriteLine(exception);
        return true; // "handled"
      });
    }
  }
}

class ch01_10
{
  void Test()
  {
    Observable.Interval(TimeSpan.FromSeconds(1))
        .Timestamp()
        .Where(x => x.Value % 2 == 0)
        .Select(x => x.Timestamp)
        .Subscribe(x => Trace.WriteLine(x));
  }

  void Test2()
  {
    IObservable<DateTimeOffset> timestamps =
        Observable.Interval(TimeSpan.FromSeconds(1))
            .Timestamp()
            .Where(x => x.Value % 2 == 0)
            .Select(x => x.Timestamp);
    timestamps.Subscribe(x => Trace.WriteLine(x));
  }

  void Test3()
  {
    Observable.Interval(TimeSpan.FromSeconds(1))
        .Timestamp()
        .Where(x => x.Value % 2 == 0)
        .Select(x => x.Timestamp)
        .Subscribe(x => Trace.WriteLine(x),
            ex => Trace.WriteLine(ex));
  }
}

class ch01_11
{
  void Test()
  {
    try
    {
      var multiplyBlock = new TransformBlock<int, int>(item =>
      {
        if (item == 1)
          throw new InvalidOperationException("Blech.");
        return item * 2;
      });
      var subtractBlock = new TransformBlock<int, int>(item => item - 2);
      multiplyBlock.LinkTo(subtractBlock,
          new DataflowLinkOptions { PropagateCompletion = true });

      multiplyBlock.Post(1);
      subtractBlock.Completion.Wait();
    }
    catch (AggregateException exception)
    {
      AggregateException ex = exception.Flatten();
      Trace.WriteLine(ex.InnerException);
    }
  }
}
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
4,867
Location
Sydney, Australia
Programming Experience
10+
Why do you think you need to do anything? Does it not compile as it is? It appears that you may have just copied the code from the chapter without actually reading the chapter. I find it hard to believe that the book doesn't tell you how to create and run a project. Do what the book instructs and then, if you encounter a specific issue, tell us exactly what you did and what happened and we can help you with that. It's not really for us to teach you the basics of using VS so you don't have to read the book you have.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
6,514
Location
Chesapeake, VA
Programming Experience
10+
I'll need to find my copy of Cleary's book. As I recall, though his initial chapter
talks about how to get some of his sample code to compile. My recollection is hazy, though since I last read the book back in 2017 or 2018, I think.

I thought that book was very well written.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
6,514
Location
Chesapeake, VA
Programming Experience
10+
Part of the problem the OP has is that he is jumping straight into Cleary's book -- a book targeted for intermediate to advanced C# programmers, but he is currently a beginning C# programmer and won't instinctively know where to plop in code fragments.
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
4,867
Location
Sydney, Australia
Programming Experience
10+
Part of the problem the OP has is that he is jumping straight into Cleary's book -- a book targeted for intermediate to advanced C# programmers, but he is currently a beginning C# programmer and won't instinctively know where to plop in code fragments.
In that case, my recommendation would be that the OP works through a beginner tutorial on the web in order to gain an understanding of those fundamentals. I've seen this movie before: someone wants to avoid having to go over the boring stuff so they can jump into the fun stuff and they end up asking question after question about that boring stuff.
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
6,514
Location
Chesapeake, VA
Programming Experience
10+
As I recall, though his initial chapter
talks about how to get some of his sample code to compile. My recollection is hazy, though since I last read the book back in 2017 or 2018, I think.
I stand corrected. Nothing in the book I have (1st edition) talks about the how to use the code fragments, or even where to download them from. It just makes mention of online resources for errata.

From what I can see in post #1, each abstract class there maps to a code fragment in chapter 1. Since the classes are declared abstract, the reader is not even meant to instantiate one of those classes. I therefore conclude that the code in post #1 are just copies that readers can look at in their text editor while reading their book.

Also as part of the foreword of the book, the Cleary writes:
Who Should Read This Book
... I do assume that you've got a fair amount of .NET experience, including an understanding of generic collections, enumerables, and LINQ. ...
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
4,867
Location
Sydney, Australia
Programming Experience
10+
I stand corrected. Nothing in the book I have (1st edition) talks about the how to use the code fragments, or even where to download them from. It just makes mention of online resources for errata.

From what I can see in post #1, each abstract class there maps to a code fragment in chapter 1. Since the classes are declared abstract, the reader is not even meant to instantiate one of those classes. I therefore conclude that the code in post #1 are just copies that readers can look at in their text editor while reading their book.

Also as part of the foreword of the book, the Cleary writes:
Based on the titles, I suspect that the second book mentioned in post #1 provides more coverage of the basics, including creating, building and running projects.
 

cjard

Well-known member
Joined
Jan 25, 2012
Messages
433
Programming Experience
10+
C#:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Linq; //probably need to install a nuget package to make this code line work
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;


namespace HelloWorld2
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            await new ch01_01().DoSomethingAsync(); //you won't be able to "new" an abstract class
        }
    }

public class ch01_01 //added public modifier so class Program can access it 
{
  public async Task DoSomethingAsync() //added public here too
  {
    int value = 13;

    // Asynchronously wait 1 second.
    await Task.Delay(TimeSpan.FromSeconds(1));

    value *= 2;

    // Asynchronously wait 1 second.
    await Task.Delay(TimeSpan.FromSeconds(1));

    Trace.WriteLine(value);
  }
}
}

It'll compile and run but probably teach you next to nothing; I've never thought console apps make for good Task async teaching studies because a console app doesn't obviously do anything else while waiting for a task to complete
 
Top Bottom