【发布时间】:2020-05-06 05:35:10
【问题描述】:
我的代码:
foreach (ListViewItem item in list.Items)
{
string url, path, host;
url = item.SubItems[0].Text; // example "www.google.com/"
path = item.SubItems[1].Text; // example = "login/"
host = (item.SubItems[2].Text); // example = "123.123.123:232";
bool ping = Request(url, path, host);
if (ping) {
item.Subitems[3].Text = "This is good";
} else {
item.Subitems[3].Text = "This is bad";
}
}
这是请求方法
public bool Request(string url, string path, string host)
{
HttpRequest httpRequest = new HttpRequest();
//a lot if code with httpRequest
if (result == "good")
return true;
else
return false;
}
所以当我在列表中放入 20 个项目并运行此代码时,此代码不会有任何错误关闭应用程序,因此我必须添加任务以使其在不关闭应用程序的情况下运行。
所以我这样做了
foreach (ListViewItem item in list.Items)
{
await Task.Run(() => {
string url, path, host;
url = item.SubItems[0].Text; // example "www.google.com/"
path = item.SubItems[1].Text; // example = "login/"
host = (item.SubItems[2].Text); // example = "123.123.123:232";
bool ping = Request(url, path, host);
if (ping) {
item.Subitems[3].Text = "This is good";
} else {
item.Subitems[3].Text = "This is bad";
}
}
}
但它给了我这个错误 当前线程必须设置为单线程单元 (STA)
【问题讨论】:
-
抱歉,为什么要添加Task来防止应用退出?