【发布时间】:2012-01-07 02:18:09
【问题描述】:
我有一个 for 循环,我希望(对于 ListBox 中的每个项目)执行一个方法。
现在发生的情况是第一个项目被选中,方法正在执行,但它没有选择第二个项目,它只是坐在那里。
你能帮忙吗?
这就是我的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]);
}
}
}
【问题讨论】:
-
为什么 listBox8.SetSelected(i, true);那么 listBox8.SelectedIndex = 0;?我的意思是那里还有其他事情发生吗?
-
你在使用signinmobile方法中的列表选择吗?如果是,那么您可以发布该代码吗?它对我来说看起来不是线程安全的
-
@rfmodulator 我只是放了这两行以确保它选择了第一项,因为没有它们,我的 for 循环就闲置着什么也不做。一旦方法完成,它就会删除选定的项目。
-
@GETah 我编辑并添加了子代码
-
@GETah,当然这不是线程安全的,他必须首先禁用 CheckForIllegalCrossThreadCalls 才能运行。 :)
标签: c# multithreading for-loop iteration