Reputation: 5047
I got a code for calling async blocks.
private delegate void MyDelegate();
void Async(MyDelegate t) {
Thread thread = new Thread(new ThreadStart(t));
thread.IsBackground = true;
thread.Start();
}
And then:
Async(delegate() {
// code
});
I'm using it, but I'm sure that this is not the right way to do this. What are the problems with this method?
Upvotes: 0
Views: 114
Reputation: 20157
Since you already have a delegate
private delegate void MyDelegate();
you can do this
new MyDelegate(delegate
{
// code
}).BeginInvoke(null, null);
It'd use thread pool threads so you don't wind up overwhelming the runtime with too many threads.
Upvotes: 1
Reputation: 1503130
There seems no point in declaring your own delegate, for one thing. Why not just:
void Async(ThreadStart t) {
Thread thread = new Thread(t);
thread.IsBackground = true;
thread.Start();
}
? Personally I can't see myself wanting to do this often enough (and with no way of finding out how the task is progressing) to warrant a separate method. If you're using .NET 4 you should look into the Task Parallel Library, which still allows you to fire off asynchronous tasks - but in a rather more fully-featured way. (EDIT: Okay, so you can't use that from .NET 2 - it's worth bearing in mind for the future though.)
You might also want to consider using the BeginInvoke
method on delegates, which allows you to start them on the thread pool easily anyway - and pass arguments:
Action<string, int> action = (name, age) => { ... };
IAsyncResult result = action.BeginInvoke("Jon", 35, null);
// Now you can use result if you want...
EDIT: You've now said you'll be doing this several times a second. Assuming this is a short-running task, you almost certainly should be using the thread-pool for this. As well as the example above, you can also use ThreadPool.QueueUserWorkItem
to add a task to the thread pool. This will be more efficient (through thread reuse) than creating a new thread each time you have a task.
Upvotes: 2