المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Threadpool help



C# Programming
10-12-2009, 06:12 AM
Hello,
Im trying to make a multithreaded proxy tester/scanner.

here is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Threading;

namespace WebProxyTest
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}

private void Main_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
}

private void btnStart_Click(object sender, EventArgs e)
{
for(int i = 0; i < lstProxies.Items.Count; i++){
string proxy = lstProxies.Items[i].ToString();

string[] proxyinfo = proxy.Split(':');
string proxyhost = proxyinfo[0];
int proxyport = Convert.ToInt32(proxyinfo[1]);
WebProxyTest test = new WebProxyTest(proxyhost, proxyport, "http://google.com/");

ThreadPool.SetMaxThreads(10, 2);
ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessProxies), test);
}
}

private void ProcessProxies(object state){
WebProxyTest test = state as WebProxyTest;
test.TestProxy();
//lstProxies.Items.Add("Result : " + test.ProxyResult);
lstResults.Items.Add("Result: " + test.ProxyResult);
}

}
}

using System;
using System.Collections.Generic;
using System.Text;

using System.IO;
using System.Web;
using System.Net;

namespace WebProxyTest
{
class WebProxyTest
{
private string proxyhost;
private int proxyport;
private string url;

private string proxy_result = "none";
public string ProxyResult {
get {
return proxy_result;
}
set {
proxy_result = value;
}
}

public WebProxyTest(string proxyhost, int proxyport, string url)
{
this.proxyhost = proxyhost;
this.proxyport = proxyport;
this.url = url;
}

public void TestProxy()
{
try
{

WebProxy proxy = new WebProxy(String.Format("http://{0}:{1}/", proxyhost, proxyport), true);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Proxy = proxy;
request.Method = "GET";

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

string result = reader.ReadToEnd();

proxy_result = "Done: Got " + result.Length;

System.Windows.Forms.Clipboard.SetText(result);

response.Close();
reader.Close();
}
catch (System.Exception ex)
{
proxy_result = "Error: " + ex.Message;
}
}
}
}


the problem is at this line:
test.TestProxy();
and/or
lstResults.Items.Add("Result: " + test.ProxyResult);

when I call a function/property of the WebProxyTest class I get an exception with something like:
"Error: The current thread is the mode Single Thread Apartment (STA) be brought before OLE calls can be made. Verify that the main function STAThreadAttribute is highlighted."

any ideas?
Thanks in advance