スレッドプールからの「新しい」意味。
以下の例を考えると、私の仮定は次のとおりです。
3番目は、私の質問の出所です。WebClient.UploadStringAsyncの定義:指定された文字列を指定されたリソースにアップロードします。これらのメソッドは、呼び出し元のスレッドをブロックしません。
これは、プールで使用可能な別のスレッドを使用することを意味しますか?これはお勧めできないテクニック(非同期内の非同期)ですか?
私の最終的な目標は、一部のデータを非同期で投稿することであり(ファイア・アンド・フォーゲット)、以前はUploadStringAsyncを使用していました。ここで、BeginInvokeを使用して周囲のコードもカプセル化することにしましたが、UploadStringAsyncを代わりに同期メソッド(UploadString())に変更する必要があるかどうかを考えています。
助けてくれてありがとう!
public class AsyncMain
{
// The delegate will be called asynchronously.
public delegate string AsyncMethodCaller(out int threadId);
public static void Main()
{
// The asynchronous method puts the thread id here.
int threadId;
//Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(AsyncDemo.TestMethod);
// Initiate the asychronous call.
IAsyncResult result = caller.BeginInvoke(out threadId, null, null);
Console.WriteLine("In AsyncMain.Main() Thread {0} does some work.", Thread.CurrentThread.ManagedThreadId);
// Call EndInvoke to wait for the asynchronous call to complete,
// and to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine("The async call executed on thread {0}, has responded with \"{1}\". The result is {2}", threadId, returnValue, result);
}
}
public class AsyncDemo
{
// The method to be executed asynchronously.
public static string TestMethod(out int threadId)
{
//get threadId, assign it.
threadId = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("TestMethod() begins at thread {0}", threadId);
//Do work
//Do ASYNC Method such as: WebClient.UploadStringAsync
return String.Format("I'm finished my work.");
}
}
これは、プールで使用可能な別のスレッドを使用することを意味しますか?
簡単な答え:はい。
UploadStringAsyncのドキュメントによると:
文字列は、スレッドプールから自動的に割り当てられるスレッドリソースを使用して非同期に送信されます。
また、BeginInvokeは、スレッドプールのスレッドを使用して非同期動作を実行します。
これはお勧めできないテクニック(非同期内の非同期)ですか?
両方のレベルで非同期動作が必要な場合は、やらなければならないことを実行します。ただし、一般的には、機能する最も単純なコードを作成することをお勧めします。したがって、1レベルの間接参照だけで解決できる場合は、それを選択することをお勧めします。
残念ながら、新しいバージョンの.NETにアップグレードすることはできません。新しいバージョンでは、タスクを使用するだけで同じことをはるかに簡単に実行できるためです。
public static void Main()
{
Task<string> task = AsyncDemo.TestMethod();
Console.WriteLine("In AsyncMain.Main() Thread {0} does some work.", Thread.CurrentThread.ManagedThreadId);
string returnValue = task.Result; // This will cause the main thread to block until the result returns.
Console.WriteLine("The async call executed on thread {0}, has responded with \"{1}\". The result is {2}", threadId, returnValue, result);
}
public class AsyncDemo
{
// The method to be executed asynchronously.
public async static Task<string> TestMethod()
{
Console.WriteLine("TestMethod() begins");
//Do work
await new WebClient().UploadStringTaskAsync("...", "...");
return String.Format("I'm finished my work.");
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加