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?
There seems no point in declaring your own delegate, for one thing. Why not just:
? 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
BeginInvokemethod on delegates, which allows you to start them on the thread pool easily anyway – and pass arguments: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.QueueUserWorkItemto 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.