Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi, I am new to threading. I would like to know if this a correct way to quickly run a function on a separate thread? Any bad issue or possible errors? Thanks

C#
public static void InvokeAsync<TParam, TResult>(Func<TParam, TResult> function, TParam parameter, Action<TResult> completedAction)
{
     BackgroundWorker bw = new BackgroundWorker();
     bw.DoWork += (sender, e) => e.Result = function(parameter);
     bw.RunWorkerCompleted += (sender, e) => completedAction((TResult)e.Result);
     bw.RunWorkerAsync();
}
Posted
Comments
M. Mohsen 3-Oct-10 18:28pm    
Does this actually work ??
Ibrahim Yusuf 3-Oct-10 21:45pm    
Yes it compiled successfully. I tested it to process value types like string or int, no problem. But I am not sure if this is the correct way to do it - especially on reference types, collection types or thread-safe types.
aidin Tajadod 3-Oct-10 23:56pm    
Why did you make it so complicated?
Ibrahim Yusuf 4-Oct-10 10:58am    
No I didn't, I was just simplified it using generics, anonymous method and lambda expression, instead of writing 2 separate event handler.
M. Mohsen 4-Oct-10 15:21pm    
I think you might be interested in reading about delegates in C#. I believe you can write a simpler code :).

I recommend you read the articles on BackgroundWorker here[^] and here[^].
 
Share this answer
 
Comments
Ibrahim Yusuf 9-Oct-10 9:58am    
Thank you ^^
Ibrahim, your sample code is correct - but strictly has nothing to do with threading.

As you pointed out, really what you're doing is wrapping the work that subscribes to the two events, and then starts the background worker. And all of that has nothing to do with what you may be doing on the background thread (the body of function) and how it interacts with memory on the invoking thread.

And, your tests proved that InvokeAsync does indeed cause a thread to do the assigned work and then report its completion status (or, at least, I assume your tests demonstrate that).

As well as the links CIDev provided, I would read and understand about:
* deadlocks (which happen when two or more threads are each waiting on locks owned by the other threads),
* what it means for code to be thread-safe and what practices and
* what technologies are available to ensure that your code is thread-safe.
 
Share this answer
 
Comments
Ibrahim Yusuf 9-Oct-10 10:03am    
I was just trying to make threading tasks simpler, but you're right, threading must be understood correctly and done carefully. Thanks for giving the right direction ^^

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900