我使用visual studio
为Windows Phone
c#
工作。我正在使用一个线程,我需要在线程完成后调用该函数,但我的问题是我的线程中有一个http调用,所以线程在http调用结束之前进入完成阶段。我只需要在http调用结束时结束线程。但现在线程在调用http调用后结束,所以我怎么能克服这个问题,谢谢。这是我的代码
void worker_DoWork(object sender, DoWorkEventArgs e)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
handle.MakeRequest(WidgetsCallBack, WidgetsErrorCallBack,
DeviceInfo.DeviceId, ApplicationSettings.Apikey);
});
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// function which i should call only after the thread is completed.
// (http cll should also be ended)
}
答案 0 :(得分:0)
没有看到http电话,你让我相信你正在做一个非同步的。因此,如果您想在不同的线程中运行http调用,那么您可以使用许多异步方法中的任何一种(例如DownloadStringAsync)。所以,你不需要一个线程来实现这一点。这有帮助吗?
已更新,可根据以下评论提供示例代码:
因此,我将使用WebClient对象并以异步方式调用URL,而不是工作者:
// Creating the client object:
WebClient wc = new WebClient();
// Registering a handler to the async request completed event. The Handler method is HandleRequest and is wrapped:
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(HandleRequest);
// Setting some header information (just to illustrate how to do it):
wc.Headers["Accept"] = "application/json";
// Making the actual call to a given URL:
wc.DownloadStringAsync(new Uri("http://stackoverflow.com"));
处理程序方法的定义:
void HandleRequest(object sender, DownloadStringCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null)
{
// Handle e.Result as there are no issues:
...
}
}