使用Thread.Abort杀死HttpWebRequest对象

Arm*_*rat 6 c# multithreading httpwebrequest

所有,我试图使用类似于下面的代码的方法取消两个并发的HttpWebRequests(以伪ish C#显示).

Main方法创建两个创建HttpWebRequests的线程.如果用户希望,他们可以通过单击按钮然后调用Abort方法来中止请求.

private Thread first;
private Thread second;
private string uri = "http://somewhere";

public void Main()
{
  first = new Thread(GetFirst);
  first.Start();

  second = new Thread(GetSecond);
  second.Start();

  // Some block on threads... like the Countdown class
  countdown.Wait();
}

public void Abort()
{
  try
  {
    first.Abort();
  }
  catch { // do nothing }

  try
  {
    second.Abort();
  }
  catch { // do nothing }
}

private void GetFirst(object state)
{
  MyHandler h = new MyHandler(uri);
  h.RunRequest();
}

private void GetSecond(object state)
{
  MyHandler h = new MyHandler(uri);
  h.RunRequest();
}
Run Code Online (Sandbox Code Playgroud)

第一个线程被SocketException中断:

A blocking operation was interrupted by a call to WSACancelBlockingCall
Run Code Online (Sandbox Code Playgroud)

第二个线程挂起在GetResponse()上.

如何以Web服务器知道连接已中止的方式中止这两个请求?,和/或,有更好的方法吗?

UPDATE

正如所建议的,一个很好的选择是使用BeginGetResponse.但是,我无法访问HttpWebRequest对象 - 它在MyHandler类中被抽象化.我修改了这个问题来证明这一点.

public class MyHandler
{
  public void RunRequest(string uri)
  {
    HttpWebRequest req = HttpWebRequest.Create(uri);
    HttpWebResponse res = req.GetResponse();
  }
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*rth 5

使用BeginGetResponse发起呼叫,然后使用Abort这个类的方法来取消它.

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest_methods.aspx

我认为Abort不适用于同步GetResponse:

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.abort.aspx

如果你必须坚持同步版本,要杀死这种情况,你所能做的只是中止线程.要放弃等待,您可以指定超时:

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.timeout.aspx

如果你需要杀死进程,我会争辩在新的AppDomain中启动它并在你想杀死请求时删除AppDomain; 而不是在主进程中中止一个线程.