控制台从线程输出

时间:2013-09-27 13:34:02

标签: multithreading c++-cli

我刚刚开始体验线程,无法获得一些基础知识。如何从间隔为10毫秒的线程写入Console?所以我有一个线程类:

public ref class SecThr
{
public:
    DateTime^ dt;
    void getdate()
    {
        dt= DateTime::Now; 
        Console::WriteLine(dt->Hour+":"+dt->Minute+":"+dt->Second); 
    }
};

int main()
{
    Console::WriteLine("Hello!");

    SecThr^ thrcl=gcnew SecThr;
    Thread^ o1=gcnew Thread(gcnew ThreadStart(SecThr,&thrcl::getdate));
}

我无法在Visual C ++ 2010 c ++ cli中编译它,得到很多错误C3924,C2825,C2146

1 个答案:

答案 0 :(得分:1)

您只是编写了错误的C ++ / CLI代码。最明显的错误:

  • 如果不完全编写System :: Threading :: Thread,则使用您使用的类的命名空间指令,如System :: Threading。
  • 在DateTime等值类型上使用^ hat,未作为编译错误发出信号但对程序效率非常不利,它会导致值被加框。
  • 没有正确构造委托对象,第一个参数是目标对象,第二个参数是函数指针。

重写它以便它起作用:

using namespace System;
using namespace System::Threading;

public ref class SecThr
{
    DateTime dt;
public:
    void getdate() {
        dt= DateTime::Now; 
        Console::WriteLine(dt.Hour + ":" + dt.Minute + ":" + dt.Second);
    }
};


int main(array<System::String ^> ^args)
{
    Console::WriteLine("Hello!");

    SecThr^ thrcl=gcnew SecThr;
    Thread^ o1=gcnew Thread(gcnew ThreadStart(thrcl, &SecThr::getdate));
    o1->Start();
    o1->Join();
    Console::ReadKey();
}
相关问题