1.
---------------------------
/// <summary>
/// 用来判断是否停止线程的变量
/// </summary>
private volatile bool m_stopThread=false;
private Thread m_threadStartSendMusic;
/// <summary>
/// 开始发送
/// </summary>
public void SendMusicInThread(int startcount,int sendcount,string sbip)
{
//若有在发送数据 停止发送
m_stopThread = true;
Thread.Sleep(106);
m_StartCount = startcount;
m_SendCount = sendcount;
m_sbip = sbip;
//新开一个线程发送数据
m_threadStartSendMusic = new Thread(SendMusic);
m_threadStartSendMusic.IsBackground = true;
m_threadStartSendMusic.Start();
}
/// <summary>
/// 发送音乐
/// </summary>
private void SendMusic()
{
m_stopThread = false;
int endCount = m_StartCount + m_SendCount;
for (int i = m_StartCount; i < endCount; i++)
{
if (m_stopThread)
{
break;
}
//do something
}
}
----------------------------------------------------------------------------------------------
2.
/// <summary>
/// 用来判断是否停止线程的变量
/// </summary>
private volatile bool m_stopThread=false;
private Thread m_threadStartSendMusic;
/// <summary>
/// 开始发送
/// </summary>
public void SendMusicInThread(int startcount,int sendcount,string sbip)
{
//若有在发送数据 停止发送
m_stopThread = true;
Thread.Sleep(106);
m_stopThread = false;
m_StartCount = startcount;
m_SendCount = sendcount;
m_sbip = sbip;
//新开一个线程发送数据
m_threadStartSendMusic = new Thread(SendMusic);
m_threadStartSendMusic.IsBackground = true;
m_threadStartSendMusic.Start();
}
/// <summary>
/// 发送音乐
/// </summary>
private void SendMusic()
{
int endCount = m_StartCount + m_SendCount;
for (int i = m_StartCount; i < endCount; i++)
{
if (m_stopThread)
{
break;
}
//do something
}
}
-------------------------------------------------------------------------------------------------
当我多次执行SendMusicInThread(。。。)方法时 为何1不能停止当前线程 然后再开线程m_threadStartSendMusic
2却能把上一个线程停掉 然后再开一个线程
就 m_stopThread 放的位置不同
而m_stopThread 我设置的是volatile 应该每次执行去判断m_stopThread的时候都是最新的值才对 为什么呢
你是如何调用 SendMusicInThread 这个函数的?
Thread.Sleep() 时间长点,比如 5000。
start方法后,线程不会马上被执行,而是等待被执行。我猜想哦,这两段代码在不同配置电脑上,会有不同结果。