How can i run a method in a thread and call a method when the thread exits
I have been searching for an answer to this but cannot find a simple example to help me understand. I am writing win form app in c# that wraps up a bunch of command line tools used for video encoding. I have a method called encodefiles i want to run this method in a thread so that the UI can still operate. Once the thread has finished I want it to call another method so i know it has finished. i can then encode the next file or finish. all depends if there are any more files to encode.
I was getting the action i wanted when i was only running a single command line tool as i was using the process object which you can attach a finished event to. I want to the same for a thread but have no idea how.
In short i want to be able to do the following with a thread instead of a process
Process myProcess = Process.Start(commandLineExe, commandlineSwit开发者_JS百科ches);
myprocess.EnableRaisingEvents = true;
myprocess.Exited += new EventHandler(myprocess_exited);
Hope that makes sense
Am using c# .NET 3.5 with visual studio 2010
well if you are using winforms and you want to run a task in background and notify when its completed use backgroundworker
and handle the DoWork(), WorkerComplete(), progressChanged() events to get your work done.
Did you take a look at the BackgroundWorker class? It gives you the option to fire 'progress changed' events.
Create one more thread. In the thread procedure for it, do:
yourMonitoredThread.Join();
CallYourProcedure(); // can be event
EDIT:
You can derive from Thread
and implement your needed event and use it encapsulated.
Maybe something like this:
public class MyThread
{
Thread _thread;
public MyThread()
{
_thread = new Thread(WorkerMethod);
}
public void Start()
{
_thread.Start();
}
private void WorkerMethod()
{
// do something useful
// [...]
//Exiting this method = exit thread => trigger event
Exited(this, EventArgs.Empty);
}
public event EventHandler Exited = delegate{};
}
精彩评论