'New' meaning from a thread pool.
Given the example below, my assumptions are:
- Main method executes on one thread (eg. thread 1)
- BeginInvoke uses available thread in pool to execute AsyncDemo.TestMethod (thread 2)
- An async method call, eg WebClient.UploadStringAsync uses another available thread (thread 3)
Number three is where my question stems from, The definition of WebClient.UploadStringAsync: Uploads the specified string to the specified resource. These methods do not block the calling thread.
Does this mean it uses another available thread in the pool? Is this an ill-advised technique (async within an async)?
My ultimate goal is to post some data asynchronously (fire and forget), and was using UploadStringAsync previously. Now I have decided to encapsulate the surrounding code with BeginInvoke as well, but thinking if I have to change the UploadStringAsync to a synchronous method instead (UploadString()).
Thanks for any help!
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.");
}
}