Console output from thread

被刻印的时光 ゝ 提交于 2019-12-11 19:39:44

问题


I've just started experiencing with thread and can't get some basics. How can i write to Console from thread with interval say 10 msec? So i have a thread class:

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));
}

I cannot compile it in my Visual c++ 2010 c++ cli, get a lot of errors C3924, C2825, C2146


回答1:


You are just writing incorrect C++/CLI code. The most obvious mistakes:

  • missing using namespace directives for the classes you use, like System::Threading, required if you don't write System::Threading::Thread in full.
  • using the ^ hat on value types like DateTime, not signaled as a compile error but very detrimental to program efficiency, it will cause the value to be boxed.
  • not constructing a delegate object correctly, first argument is the target object, second argument is the function pointer.

Rewriting it so it works:

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();
}


来源:https://stackoverflow.com/questions/19052143/console-output-from-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!