Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Parallel Programming with .NET

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 553
    Comment on it

    There might be some scenario in your code, where some of the tasks should be performed in the background without affecting the current task. Some time we have scenario, where we needed to fire the function, which consists of some function call, where the result of the function call is not used in the current function. we just needed to run it in the background, so there was no reason to wait for the function call result. We need to execute the next statement without waiting for the response, which can be easily achieved by Task factory.

    So here is a simple example of Task.Factory.StartNew

     

    using System;
    using System.Threading.Tasks;
    
    namespace FireAndForget
    {
        class Program
        {
            static int a, b;
            public static void Add(int x, int y)
            {
                int z = x + y;
                Console.WriteLine("Add Result {0}", z);
            }
            static void Main(string[] args)
            {
                Console.WriteLine("Enter first value for addition");
                a = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Enter first value for addition");
                b = Convert.ToInt32(Console.ReadLine());
                Task.Factory.StartNew(() => Add(a, b));
                Console.WriteLine("I'm next to Add");
                Console.ReadKey();
    
            }
        }
    }

    From the code, mentioned above, you can observe that the static main function is calling the Add function, where the result of Add function is not used in the Main function, so without implementing the task factory, the statement next to add function call will be executed after the Add function completes its process
     

    Output:

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: