0

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

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Bushido
  • 29
  • 6

1 Answers1

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();
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Thanks a lot! The second question is - how can i get time from this thread on the console with frequency 1 sec (update the string with date)? – Bushido Sep 27 '13 at 14:01
  • 1
    That's another question, you need to click the Ask Question button to ask it. After you checked the System::Timers::Timer class anyway. – Hans Passant Sep 27 '13 at 14:07