大家好,有一个线程,在循环内执行,完成一次线程时间长短不一定,执行完成后再进入下一循环参数,如何实现,多谢!!
这是一个根据IP获取详细信息的程序,参数是IP起始和结束地址段,请问如何修改,代码如下:
private List<Thread> ThreadList;
private BindingList<taobaoIPdata> taobaoIPdataList;
private void Load(string beginIP,string endIP)
{
StartIP = IPHelper.Ip2Long(beginIP);
CurrentCollectIP = StartIP - 1;
EndIP = IPHelper.Ip2Long(endIP);
ThreadCount = (int)this.nud_ThreadCount.Value;
taobaoIPdataList = new BindingList<taobaoIPdata>();
ThreadList = new List<Thread>();
ThreadList.Add(new Thread(GetTaobaoData) { IsBackground = true });
}
private void btn_begin_Click(object sender, EventArgs e)
{
Load( txt_Start.Text , txt_End.Text);
thread.Start();
}
private long GetCurrentIp()
{
long curip = System.Threading.Interlocked.Increment(ref CurrentCollectIP);
return curip;
}
/// <summary>
/// 线程中采集的方法
/// </summary>
private void GetTaobaoData()
{
long currentipLong = GetCurrentIp();
while (currentipLong <= EndIP)
{
try
{
CaptureTaobaoIPData(currentipLong);
}
catch (Exception ex)
{
TextLog.SetString(currentipLong + ex.Message);
}
currentipLong = GetCurrentIp();
}
}
/// <summary>
/// 描述:线程中采集并得到IP
/// </summary>
private void CaptureTaobaoIPData(long currentipLong)
{
string ip = IPHelper.Long2Ip(currentipLong);
string url = string.Format(UrlFomat, ip);
string js =HttpHelper. HttpRequest(url, Encoding.UTF8);
taobaoIPdata m = Newtonsoft.Json.JsonConvert.DeserializeObject<TaobaoJsonData>(js).data;
m.ipLong = currentipLong;
taobaoIPdataList.Add(m);
//todo: 存储IP到数据库
}
for()
{
task.factory.startnew(()=>{
//dosomething...
});
task.wait();
}
你好,根据我上面给出的代码,具体在什么位置加循环比较好呢?
@我的理想之路: for循环啊,里面是一个task,task.wait()这句会等到task执行完成后才往下执行
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { CancellationTokenSource s = new CancellationTokenSource(); CancellationToken token = s.Token; for (int i = 0; i < 5000; i++) { Thread th = new Thread(new ParameterizedThreadStart((o) => { Console.WriteLine(o.ToString()); })); th.Start(i); token.WaitHandle.WaitOne(50); } } } }
您好,50MS不一定可以完成一个线程,我已经把问题代码写出来了,请参考一下,多谢。
@我的理想之路: WaitOne不带参数就会一直等待下去.
@水晶途途: 50有些少,可否换成事件响应机制,5000个计数,是否要产生5000个线程?
如果根据我提供的代码,这个循环加在哪里比较合适?
public static async void Run() { var rm = new Random(); for (var i = 0; i < 100; i++) { await Task.Run(async () => { await Task.Delay(rm.Next(200, 1000)); Console.WriteLine(i); }); } }
用变量控制吧。我就这样。
一个整数变量和后面的两个操作就ok.
Interlocked.Increment
Interlocked.Decrement
class ThreadA{
run(){
//dosth
if(){
new ThreadA().start();
}
}
}
main{
new ThreadA().start();
}
Task task.Wait就可以啊。 不是有人说了吗、