C# 4.0 を使用して、以下に示す関数 foo() 内から UI を更新する簡単で堅牢な方法を知りたいです。処理された URL の数と検出された不良リンクの数を表示するテキスト ボックスを更新する必要があります。私が非同期タスクで採用した一般的なアプローチは、ここで見つけたアプローチに基づいています。
HttpWebRequest (.NET) を非同期で使用するには?
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 ??
}