Answered multithreading and asynchronous programming together

etl2016

Active member
Joined
Jun 29, 2016
Messages
39
Programming Experience
3-5
hi,

As I understand it, multithreading is for getting full potential of machine's processing capacity by splitting cpu-bound workload. And, Asynchronous programming is to get best use of clock-time to carry on independent tasks simultaneously. Am, trying to integrate these two to address scenarios of large scale data processing, where both features are helpful. But, am not finding many best practices on this approach (could be that, this approach is discouraged in the first place - so, please feedback - thanks)

The below code setup is throwing an object reference error: Is this design approach correct, if so, could you please suggest a fix to the error, thanks.

C#:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace threadAsync
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("MAIN : Hello World!");
            Calling_method_async();

        }
        private async void Calling_method_async()
        {
            var th = new Thread(async () => await Called_method_async());
            th.Start();
                      
        }
        public async Task<int> Called_method_async()
        {
            await Task.Delay(4);
            return 42;
        }
    }
}
 
That issue is that the main thread is terminating before the lambda for the thread body and the task can complete.

Your code above is equivalent to:

C#:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace threadAsync
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("MAIN : Hello World!");
            var th = new Thread(async () => await Called_method_async());
            th.Start();
        }

        public async Task<int> Called_method_async()
        {
            await Task.Delay(4);
            return 42;
        }
    }
}

Notice how the Main() terminates right after starting a thread.
 
As I understand it, multithreading is for getting full potential of machine's processing capacity by splitting cpu-bound workload. And, Asynchronous programming is to get best use of clock-time to carry on independent tasks simultaneously.
I wish I could find the an older blog post about the two different kinds of asynchrony, but, for now this is is equally useful:
 
Back
Top Bottom