How to create a thread in c#

904 Views Asked by At

Can I create a class that inherited from thread class in c#, for my Windows Phone application.

For example : if my class name is 'MyClass' I want to start the thread as new MyClass().Start();

Like in following Java example

public class TagIndexer 
{
    private static class Task 
    {
        private String docId;
        private String tags;
        private String extension;

        public Task(String docId, String tags, String extension) 
        {
            this.docId = docId;
            this.tags = tags;
            this.extension = extension;
        }
    }

    private static final LinkedList<Task> queue = new LinkedList<Task>();
    private static boolean isWorking = false;

    private static class TaskRunner extends Thread 
    {
        @Override
        public void run() 
        {
            while (true) 
            {
                Task task;
                synchronized (queue) 
                {
                    task = queue.poll();
                    if (null == task) 
                    {
                        isWorking = false;
                        break;
                    }
                    isWorking = true;
                }
                /*
                 * PROCESSING CODE
                 */
            }
        }
    }

    public static void addDocument(int docId, String tags, String extension) 
    {
        Task task = new Task(Integer.toString(docId), tags, extension);

        synchronized (queue) 
        {
            queue.add(task);
            if (!isWorking) 
            {
                new TaskRunner().start();
            }
        }
    }
}
3

There are 3 best solutions below

0
On BEST ANSWER
new MyClazz().Start();

-

public abstract class MyThread
{
    public abstract void Run();

    public void Start()
    {
        new Thread(Run).Start();
    }
}

public class MyClazz : MyThread
{
    public override void Run()
    {
        Console.WriteLine("Hello World");
    }
}
0
On

On Windows Phone, Thread is a sealed class, therefore you cannot inherit from it. If you want to keep the task-based approach, you can just create a class that will wrap a thread instance. Something like:

public abstract class Task
{
    protected Thread InternalThread { get; set; }

    protected abstract void Run();

    public void Start()
    {
        this.InternalThread = new Thread(this.Run);
        this.InternalThread.Start();    
    }
}

Of course, it's just an example. You would have to add some synchronization mechanism to prevent the Start method from creating multiple threads if called more than once.

Then you can inherit it to create custom tasks:

public class MyTask : Task
{
    protected override void Run()
    {
        // Do something
    }
}
0
On