使用 C# 4.0,我想知道一种从下面显示的函数 foo() 中更新 UI 的简单可靠的方法。我需要更新一些显示处理的 url 数量和找到的坏链接数量的文本框。我对异步任务采取的一般方法是基于我在这里找到的一种方法:
Pseudo Code in my code-behind on the form:
1. populate a ConcurrentBag
2. Task.Factory.StartNew ( () =>
Parallel.ForEach( ConcurrentBag, (d) =>
{
MyAsyncTask(d);
}
MyAsyncTask 会:
<snip>
try
{
IAsyncResult result = myWebRequest.BeginGetResponse (
new AsyncCallback( foo, state);
ThreadPool.RegisterWaitForSingleObject(
result.AsyncWaitHandle,
new WaitOrTimerCallback(TimeoutCallback),
state,
(MSEC * 1000),
true
);
}
catch (Exception ex) {}
private void foo(IAsyncResult result)
{
RequestState state = (RequestState)result.AsyncState;
WebRequest request = state.webRequest;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
//update the UI ??
}