我有一个希望(针对ListBox
中的每个项)执行方法的for
循环。
现在发生的情况是,第一个项目被选中,方法被执行,但它没有选择第二个项目,它只是坐在那里。
你能帮上忙吗?
这是我的for
循环的样子:
for(int i = 0; i < listBox8.Items.Count; i++) {
listBox8.SetSelected(i, true);
listBox8.SelectedIndex = 0;
Thread t = new Thread(signinmobile);
t.Start();
CheckForIllegalCrossThreadCalls = false;
}
这是我的副手:
public void signinmobile()
{
string yourString = listBox8.SelectedItem.ToString();
string[] strArray = yourString.Split(':');
System.Net.ServicePointManager.Expect100Continue = false;
string postData = "authenticity_token=401538d41ace8f334c3d&username=" + strArray[0] + "&password=" + strArray[1] + "";
CookieContainer tempCookies = new CookieContainer();
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteData = encoding.GetBytes(postData);
HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create("https://mobile.twitter.com/session");
postReq.Method = "POST";
postReq.KeepAlive = true;
postReq.CookieContainer = tempCookies;
postReq.ContentType = "application/x-www-form-urlencoded";
postReq.Referer = "https://mobile.twitter.com/session";
postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)";
postReq.ContentLength = byteData.Length;
Stream postreqstream = postReq.GetRequestStream();
postreqstream.Write(byteData, 0, byteData.Length);
postreqstream.Close();
HttpWebResponse postresponse = default(HttpWebResponse);
postresponse = (HttpWebResponse)postReq.GetResponse();
tempCookies.Add(postresponse.Cookies);
StreamReader postreqreader = new StreamReader(postresponse.GetResponseStream());
string accountstatus = postreqreader.ReadToEnd();
webBrowser1.DocumentText = accountstatus;
if (accountstatus.Contains("Sign in information is not correct"))
{
listBox9.Items.Add(listBox8.SelectedItem.ToString() + "\r");
while (listBox8.SelectedItems.Count > 0)
{
listBox8.Items.Remove(listBox8.SelectedItems[0]);
}
}
else
{
listBox2.Items.Add(listBox8.SelectedItem.ToString() + "\r");
while (listBox8.SelectedItems.Count > 0)
{
listBox8.Items.Remove(listBox8.SelectedItems[0]);
}
}
}
发布于 2011-11-26 22:16:32
下面的行总是为每个循环周期选择第一项
listBox8.SelectedIndex = 0;
我相信您完全可以删除这一行,因为前一行(listBox8.SetSelected(i, true);
)已经进行了选择
编辑:问题更新后的
我觉得这里可能会有例外发生。在signinmobile
方法调用周围添加try/catch(Exception ex)
块,并告诉我们是否处理了eny异常。
顺便说一句,为什么你要在另一个线程中运行方法?看起来有线程同步问题,所以如果列表包含两个以上的项目,多个线程将运行并删除列表中的项目,然后调用SetSelected
失败,因为它缓存的索引值i
当前不存在,因为一些线程已经删除了项目...因此,在单线程中运行所有线程,或者在t.Start()
之后执行t.Join()
,这样主线程将等待工作线程完成,它们将继续下一个循环周期。
发布于 2011-11-26 22:15:38
您再次将选定的索引设置为0。这是第一项。所以循环的每一次迭代都停留在第一项。
发布于 2011-11-26 22:16:27
您每次都会将SelectedIndex
重置为0
,因此它不会向前移动...只需删除该行即可。
https://stackoverflow.com/questions/8282016
复制