⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threadabort.cpp

📁 Visual_C++[1].NET_Bible1 Visual_C++宝典书中的全部源码
💻 CPP
字号:
#include "stdafx.h"

#using <mscorlib.dll>
#include <tchar.h>
#include <math.h>

using namespace System;
using namespace System::Threading;

__gc class CWorkerThread
{
public:
	CWorkerThread(int iThreadId, int nTasksToPerform);

public:
  void Start();

protected:
	void ThreadMethod();

public:
  Thread* m_pThread;

protected:
  int m_iThreadId;
  int m_nTasksToPerform;
};

CWorkerThread::CWorkerThread(int iThreadId, int nTasksToPerform)
: m_iThreadId(iThreadId), m_nTasksToPerform(nTasksToPerform)
{
  // Create thread
  m_pThread = new Thread(new ThreadStart(this, &CWorkerThread::ThreadMethod));	
}

void CWorkerThread::Start()
{
  // Start thread
  if (m_pThread)
  {
    m_pThread->Start();
  }
}

void CWorkerThread::ThreadMethod()
{
  try
  {
    Console::WriteLine("[CWorkerThread::ThreadMethod] Thread {0} has initialized to do {1} tasks", 
                        __box(this->m_iThreadId),
                        __box(this->m_nTasksToPerform));

    for (int i = 0; i < m_nTasksToPerform; i++)
	  {		
      Console::WriteLine("[CWorkerThread::ThreadMethod] Thread {0} Performing task {1} of {2}", 
                          __box(m_iThreadId),
                          __box(i+1),
                          __box(m_nTasksToPerform));
      Console::WriteLine("[CWorkerThread::ThreadMethod] Sleeping for 1 second to simulate work");
      Thread::Sleep(1000);
	  }

    Console::WriteLine("[CWorkerThread::ThreadMethod] Thread {0} finished working", 
                        __box(m_iThreadId));
  }
  catch(ThreadStateException* pe)
  {
    Console::WriteLine("Exception of type {0} caught", pe->GetType());
  }
}

int _tmain(void)
{   
  CWorkerThread* pWorkerThread;

  Console::WriteLine("[_tmain] Starting first thread");

  pWorkerThread = new CWorkerThread(1, 10);

  pWorkerThread->Start();

  Console::WriteLine("[_tmain] Sleeping for 1 second");
  Thread::CurrentThread->Sleep(1000);

  Console::WriteLine("[_tmain] Aborting worker thread");
  pWorkerThread->m_pThread->Abort();

  Console::ReadLine();

  return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -