我真的很難在Visual C++/CLR中使用Thread編程。我搜查了很多,在互聯網上發現了很多資料,包括官方資源,但我仍然感到困惑。 C++/CLR的資源非常少。它們大多數用於C#或舊式C++。我嘗試運行這個簡單的代碼。我選擇了一個類型爲clr console applicatioN的新項目,並將下面的代碼放在那裏,但是我收到了錯誤信息,我並沒有對其進行解釋。在C++/CLR中的線程編程
// thread_clr.cpp : main project file.
#include "stdafx.h"
using namespace System;
using namespace System;
using namespace System::Threading;
class MessagePrinter;
// class ThreadTester demonstrates basic threading concepts
class ThreadTester
{
static int Main()
{
// Create and name each thread. Use MessagePrinter's
// Print method as argument to ThreadStart delegate.
MessagePrinter printer1 = gcnew MessagePrinter();
Thread thread1 = gcnew Thread (gcnew ThreadStart(printer1.Print));
thread1.Name = "thread1";
MessagePrinter printer2 = gcnew MessagePrinter();
Thread thread2 = gcnew Thread (gcnew ThreadStart(printer2.Print));
thread2.Name = "thread2";
MessagePrinter printer3 = gcnew MessagePrinter();
Thread thread3 = gcnew Thread (gcnew ThreadStart(printer3.Print));
thread3.Name = "thread3";
Console.WriteLine("Starting threads");
// call each thread's Start method to place each
// thread in Started state
thread1.Start();
thread2.Start();
thread3.Start();
Console.WriteLine("Threads started\n");
} // end method Main
}; // end class ThreadTester
class MessagePrinter
{
private int sleepTime;
private static Random random = gcnew Random();
// constructor to initialize a MessagePrinter object
public MessagePrinter()
{
// pick random sleep time between 0 and 5 seconds
sleepTime = random.Next(5001);
}
//controls Thread that prints message
public void Print()
{
// obtain reference to currently executing thread
Thread current = Thread.CurrentThread;
// put thread to sleep for sleepTime amount of time
Console.WriteLine(current.Name + " going to sleep for " + sleepTime);
Thread.Sleep (sleepTime);
// print thread name
Console.WriteLine(current.Name + " done sleeping");
} // end method Print
} // end class MessagePrinter
請幫忙。或者更好的是,請引導我參加一些教程或其他影響。我明白,這不是一個教程網站,我不是問一個,但我會感激,如果有人可以至少指出了C++/CLR線程的資源。 C++/CLR Winform線程。真的很感激它
問候
有些錯誤是:
'PRINTER1' 使用未定義類MessagePrinter '打印':不是的 成員 '系統::的Int32'「系統:: Threading :: ThreadStart':a 委託構造函數需要2個參數 '系統::線程::線程::線程':沒有適當的默認 構造函數可用'System :: Threading :: Thread :: Thread' :no 適當的默認構造函數可用'語法錯誤:'int'sho在'未被管理的' 'MessagePrinter'可能沒有聲明一個全局或靜態變量,或一個 成員的引用gc堆中的對象的本機類型 ' MessagePrinter :: random':你不能在原生類型'MessagePrinter :: random'中嵌入參考 類型'System :: Random'的實例: 只有靜態常量整型數據成員可以在 類中被初始化' MessagePrinter」前應先‘:’‘無效’應該是 前面加‘:’
那麼你會得到什麼錯誤?我懷疑你會在這裏找到讀者,更不用說其他人的屏幕輸出了。 – nvoigt
@nvoigt ...對不起,這是我的煩惱,我正在咆哮,因爲我被困在這裏,爲過去的1天半的時間...已更新的問題 – user2572521