【问题标题】:How to start a thread in another class in C#如何在 C# 中的另一个类中启动线程
【发布时间】:2014-07-29 19:32:26
【问题描述】:

我有以下 3 个课程。我不能调用另一个类中的线程,但我用 main 声明了它,因为它可以被调用。

我收到以下错误:

UseThreads.Thread1 '是一种类型',但用作'变量'

private void Mouse_Tracking()
{
    ///
}

如何调用另一个类中的线程?

using System.Threading;

namespace UseThreads
{

public partial class from1 : Form
    {      

        private void btn_start_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(thread1));
            thread.Start();          

        }       
    }
}

下一个

using System.Threading;

namespace UseThreads
{
    class thread1
    {
        public void run()
        {
            int iterations = 10;
            try
            {
                for (int i = 0; i < iterations; i++)
                {
                    Console.WriteLine("From Thread1");
                    Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}

最后一个

using System.Threading;

namespace UseThreads
{
    class thread2
    {
        public void run()
        {
            int iterations = 10;
            try
            {
                for (int i = 0; i < iterations; i++)
                {
                    Console.WriteLine("From Thread 2");
                    Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}

为什么会这样?如何调用在单独的类中声明的线程?

【问题讨论】:

  • 等等,ThreadStart 不是代表,因此应该采用方法的名称吗?

标签: c# multithreading class methods


【解决方案1】:

您需要创建一个实例,并传递 run 方法:

var th = new thread1();
Thread thread = new Thread(new ThreadStart(th.run));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多