帮助在 C# 中线程化 HttpWebRquest

发布于 2024-08-15 09:25:25 字数 1657 浏览 4 评论 0原文

大家好,只是想知道是否有人可以帮助我尝试正确地线程化我的应用程序,我不断地遇到一个又一个的障碍,我从来没有弄清楚应用程序中的线程化。我尝试遵循此 http://www.developerfusion.com/code/4654/异步-httpwebrequest/ 教程。

基本上我只是想阻止我的请求挂起我的应用程序

public class Twitter
{
    private const string _username = "****",
        _password = "****";

    private WebResponse webResp;

    public string getTimeLine()
    {
        Thread thread = new Thread(new ThreadStart(TwitterRequestTimeLine));
        thread.IsBackground = true;
        thread.Start();

        using (Stream responseStream = webResp.GetResponseStream())
        {
            //
            using (StreamReader reader = new StreamReader(responseStream))
            {
                return reader.ReadToEnd();
            }
        }
    }

    private void TwitterRequestTimeLine()
    {
        string aUrl = "http://168.143.162.116/statuses/home_timeline.xml";
        HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(aUrl);
        SetRequestParams(request);  
        request.Credentials = new NetworkCredential(_username, _password);
        //WebResponse tempResp = request.GetResponse();
        ThreadState state = new ThreadState();
        IAsyncResult result = request.BeginGetResponse(new AsyncCallback(???), ???);

    }



      private static void SetRequestParams( HttpWebRequest request )
  {
      request.Timeout = 500000;
      request.Method = "POST";
      request.ContentType = "application/x-www-form-urlencoded";
      request.UserAgent = "AdverTwitment";
  }
}
}

任何人的帮助都会非常有用

Hi guys just wondering if somebody could help me try and correctly thread my application, I am constantly hitting an hurdle after another, I have never been to clued up on threading in applications. I have tryed following this http://www.developerfusion.com/code/4654/asynchronous-httpwebrequest/ tutorial.

basically I'm just trying to stop my request from hanging my application

public class Twitter
{
    private const string _username = "****",
        _password = "****";

    private WebResponse webResp;

    public string getTimeLine()
    {
        Thread thread = new Thread(new ThreadStart(TwitterRequestTimeLine));
        thread.IsBackground = true;
        thread.Start();

        using (Stream responseStream = webResp.GetResponseStream())
        {
            //
            using (StreamReader reader = new StreamReader(responseStream))
            {
                return reader.ReadToEnd();
            }
        }
    }

    private void TwitterRequestTimeLine()
    {
        string aUrl = "http://168.143.162.116/statuses/home_timeline.xml";
        HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(aUrl);
        SetRequestParams(request);  
        request.Credentials = new NetworkCredential(_username, _password);
        //WebResponse tempResp = request.GetResponse();
        ThreadState state = new ThreadState();
        IAsyncResult result = request.BeginGetResponse(new AsyncCallback(???), ???);

    }



      private static void SetRequestParams( HttpWebRequest request )
  {
      request.Timeout = 500000;
      request.Method = "POST";
      request.ContentType = "application/x-www-form-urlencoded";
      request.UserAgent = "AdverTwitment";
  }
}
}

anyone help would be greatly appricated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

前事休说 2024-08-22 09:25:25

您确实不需要线程化 HttpWebRequest。

当您将 BeginGetResponse() 和 EndGetResponse() 与 HttpWebRequest 一起使用时,它已经为您使用了后台线程以便异步工作。没有理由将其推入后台线程。

至于用法: HttpWebRequest.BeginGetResponse 演示一个完整的异步请求。

You really don't need to thread HttpWebRequest.

When you use BeginGetResponse() and EndGetResponse() with HttpWebRequest, it already uses a background thread for you in order to work asynchronously. There is no reason to push this into a background thread.

As for usage: The help for HttpWebRequest.BeginGetResponse demonstrates a complete, asynchronous request.

时光无声 2024-08-22 09:25:25

如果这是一个 WinForms 应用程序,那么在执行 WebRequest 时保持 GUI 响应的最简单方法是使用 BackgroundWorker 组件。在表单上放置一个BackgroundWorker 并调用其RunWorkAsync() 方法。将执行 WebRequest 的代码并在 DoWork 事件处理程序中读取 Response。

If this is a WinForms app, the easiest way to keep the GUI responsive while executing the WebRequest is to use a BackgroundWorker component. Drop a BackgroundWorker on your form and call its RunWorkAsync() method. Put the code to execute the WebRequest and read the Response in the DoWork event handler.

无名指的心愿 2024-08-22 09:25:25

尝试使用鲁本斯建议的 AsyncCallback,但将回调调用到单独的方法中以将数据加载到其目的地。如果 getTimeline 方法没有立即返回,则会导致应用程序挂起,因为 UI 线程正在运行请求本身。

如果您在请求完成后使用单独的 AsyncCallback 进行调用并让它加载数据,则该方法将立即返回,并且您的 UI 线程可以在等待时执行其他操作。

Try using an AsyncCallback like Rubens suggested but have the callback call into a separate method to load the data to its destination. If the getTimeline method doesn't return immediately it will cause the application to hang, because the UI Thread is what is running the request itself.

If you use a separate AsyncCallback to be called after the request is done and have it load the data then the method will return immediately and your UI thread can do other things while it waits.

人疚 2024-08-22 09:25:25

这个怎么样:

private string getTimeLine()
{
    string responseValue = "";
    string aUrl = "http://168.143.162.116/statuses/home_timeline.xml";
    AutoResetEvent syncRequest = new AutoResetEvent(false);
    WebRequest request = WebRequest.Create(aUrl);
    request.Method = "POST";
    request.BeginGetResponse(getResponseResult =>
    {
        HttpWebResponse response = 
            (HttpWebResponse)request.EndGetResponse(getResponseResult);
        using (StreamReader reader = 
           new StreamReader(response.GetResponseStream()))
        {
            responseValue = reader.ReadToEnd();
        }

        syncRequest.Set();
    }, null);

    syncRequest.WaitOne();
    return responseValue;
}

编辑:好吧,我试图保留一个返回字符串的方法,这就是我使用AutoResetEvent的原因;如果您使用 BackgroundWorker,您会在数据可用时收到通知:

BackgroundWorker worker = new BackgroundWorker();
string responseValue = "";
worker.RunWorkerCompleted += (sender, e) =>
{
    // update interface using responseValue variable
};
worker.DoWork += (sender, e) =>
{
    string aUrl = "http://168.143.162.116/statuses/home_timeline.xml";
    WebRequest request = WebRequest.Create(aUrl);
    // .. setup
    using(StreamReader reader = 
      new StreamReader(request.GetResponse().GetResponseStream()))
        responseValue = reader.ReadToEnd();
};
worker.RunWorkerAsync();

What about this:

private string getTimeLine()
{
    string responseValue = "";
    string aUrl = "http://168.143.162.116/statuses/home_timeline.xml";
    AutoResetEvent syncRequest = new AutoResetEvent(false);
    WebRequest request = WebRequest.Create(aUrl);
    request.Method = "POST";
    request.BeginGetResponse(getResponseResult =>
    {
        HttpWebResponse response = 
            (HttpWebResponse)request.EndGetResponse(getResponseResult);
        using (StreamReader reader = 
           new StreamReader(response.GetResponseStream()))
        {
            responseValue = reader.ReadToEnd();
        }

        syncRequest.Set();
    }, null);

    syncRequest.WaitOne();
    return responseValue;
}

EDIT: Ok, I tried to keep a method returning a string, that's why I used AutoResetEvent; If you use a BackgroundWorker, you'll get notified when your data is available:

BackgroundWorker worker = new BackgroundWorker();
string responseValue = "";
worker.RunWorkerCompleted += (sender, e) =>
{
    // update interface using responseValue variable
};
worker.DoWork += (sender, e) =>
{
    string aUrl = "http://168.143.162.116/statuses/home_timeline.xml";
    WebRequest request = WebRequest.Create(aUrl);
    // .. setup
    using(StreamReader reader = 
      new StreamReader(request.GetResponse().GetResponseStream()))
        responseValue = reader.ReadToEnd();
};
worker.RunWorkerAsync();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文