Passing data to threads

There are two ways to pass data to threads. The first one is using a structure. The second one is using a class.

Passing data using structure:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadPrograms
{
    public struct Data
    {
        public string Message;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Data d = new Data();
            d.Message = "pakistan";

            var t1 = new Thread(ThreadWithParameters);

            t1.Start(d);
        }

        static void ThreadWithParameters(object o)
        {
            Data d = (Data)o;
            Console.WriteLine("Running in Thread, Message: {0}", d.Message);
        }

        
    }
}

We can also pass data to threads by declaring class variables and defining thread methods within the same class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadPrograms
{
    public class MyThread
    {
        private string data;

        public MyThread(string data)
        {
            this.data = data;
        }

        public void ThreadMain()
        {
            Console.WriteLine("Running in thread, data: {0}", data);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyThread mt = new MyThread("pakistan");
            var t1 = new Thread(mt.ThreadMain);
            t1.Start();
        }
    }
}

 

 

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *

Spam Protection by WP-SpamFree