Invoking a method by multiple threads concurrently and report progress of each thread
I want to create a windows application in c# that will invoke a method by multiple threads concurrently. And report start and开发者_C百科 completion of each thread on the Windows form sreen.
Method to be invoked takes two parameters and returns a object.
Please help.
A response would be highly appreciated.
Thanks in advance.
From http://www.albahari.com/threading/#_Entering_the_Thread_Pool_via_TPL
static void Main()
{
Func<string, int> method = Work;
method.BeginInvoke ("test", Done, method);
// ...
//
}
static int Work (string s) { return s.Length; }
static void Done (IAsyncResult cookie)
{
var target = (Func<string, int>) cookie.AsyncState;
int result = target.EndInvoke (cookie);
Console.WriteLine ("String length is: " + result);
}
Basically, "Work" is the method you want to run on another thread. "Done" is the method you want to be called when "Work" is finished - you would put your status reporting code here. method.BeginInvoke takes the same parameters as Work does, plus two other parameters: the callback, and state information, which can be whatever you want. The callback function will need to take one parameter: an IAsyncResult. You can access the state info you pass in by getting the AsyncState of the IAsyncResult. In the example above, "target" refers to the same thing as "method". This is useful - it means that you can call "EndInvoke" on method/target, which will give you the return value that you need. "result" is the return value of "Work."
If you need multiple threads, just have multiple delegates (like "method" in the example above), and BeginInvoke all of them, one after another. You can make them all have the same callback, or they can have different callbacks. It's up to you.
Hope this helps!
精彩评论