2013-09-27 60 views
0

我剛剛開始體驗線程,無法獲得一些基本知識。我怎麼能從間隔10毫秒的線程寫入控制檯?所以我有一個線程類:線程的控制檯輸出

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

你只是寫不正確的C++/CLI代碼。最明顯的錯誤:

  • 使用命名空間指令,您使用的類,如System ::線程,需要缺少如果你不完全寫入系統::線程::主題。
  • 在像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(); 
} 
+0

非常感謝!第二個問題是 - 我如何從頻率爲1秒的控制檯上的這個線程獲取時間(用日期更新字符串)? – user2809652

+1

這是另一個問題,你需要點擊Ask Question按鈕來提問。無論如何你檢查了System :: Timers :: Timer類之後。 –