所以我一直在尝试创建一些代码,以在wire循环中发送数据,特别是通过udpclient向服务器发送的数据包。
static void doSend(string ip, int port)
{
while (isSending)
{
_sockMain = new UdpClient(ip, port);
// Code for datagram here, took it out
_sockMain.Send(arr_bData, arr_bData.Length);
}
}
但是,当我称之为"停止"方法时,它会陷入恒定循环中,并且不会出现。我该如何将WARY循环放入线程中?因此,我可以停止停止线程,取消循环?
它挂起,因为您的dosend方法在UI线程上工作。您可以使用以下类之类的东西使其在单独的线程上运行,也可以使用BackgroundWorkerclass
public class DataSender
{
public DataSender(string ip, int port)
{
IP = ip;
Port = port;
}
private string IP;
private int Port;
System.Threading.Thread sender;
private bool issending = false;
public void StartSending()
{
if (issending)
{
// it is already started sending. throw an exception or do something.
}
issending = true;
sender = new System.Threading.Thread(SendData);
sender.IsBackground = true;
sender.Start();
}
public void StopSending()
{
issending = false;
if (sender.Join(200) == false)
{
sender.Abort();
}
sender = null;
}
private void SendData()
{
System.Net.Sockets.UdpClient _sockMain = new System.Net.Sockets.UdpClient(IP, Port);
while (issending)
{
// Define and assign arr_bData somewhere in class
_sockMain.Send(arr_bData, arr_bData.Length);
}
}
}
您可以使用背景工作人员线程http://www.dotnetperls.com/backgroundworker并内部()将您的时循环放置。您可以使用cancelAsync()停止代码,并设置backgroundWorker1.WorkerSupportsCancellation == true
BackgroundWorker bw = new BackgroundWorker();
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
// Run your while loop here and return result.
result = // your time consuming function (while loop)
}
// when you click on some cancel button
bw.CancelAsync();
static bool _isSending;
static void doSend(string ip, int port)
{
_isSending = true;
while (_isSending)
{
_sockMain = new UdpClient(ip, port);
// ...
_sockMain.Send(arr_bData, arr_bData.Length);
}
}
static void Stop()
{
// set flag for exiting loop here
_isSending = false;
}
还考虑在pascalcase中命名您的方法,即DoSend
(甚至StartSending
都会更好),StopSending
。
使用BREAK
语句?