如何在线程中运行方法并在线程退出时调用方法
我一直在寻找这个问题的答案,但找不到一个简单的例子来帮助我理解。我正在用 C# 编写 win 表单应用程序,其中包含一堆用于视频编码的命令行工具。我有一个名为 encodefiles 的方法,我想在线程中运行此方法,以便 UI 仍然可以运行。一旦线程完成,我希望它调用另一个方法,这样我就知道它已经完成。然后我可以编码下一个文件或完成。一切都取决于是否还有更多文件需要编码。
当我只运行一个命令行工具时,我得到了我想要的操作,因为我正在使用可以将完成的事件附加到的进程对象。我想对一个线程做同样的事情,但不知道如何做。
简而言之,我希望能够使用线程而不是进程执行以下操作
Process myProcess = Process.Start(commandLineExe, commandlineSwitches);
myprocess.EnableRaisingEvents = true;
myprocess.Exited += new EventHandler(myprocess_exited);
希望这是有意义的
我使用 c# .NET 3.5 和 Visual Studio 2010
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, commandlineSwitches);
myprocess.EnableRaisingEvents = true;
myprocess.Exited += new EventHandler(myprocess_exited);
Hope that makes sense
Am using c# .NET 3.5 with visual studio 2010
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,如果您使用 winforms 并且希望在后台运行任务并在其完成时发出通知,请使用 backgroundworker
并处理 DoWork()、WorkerComplete()、progressChanged() 事件以完成工作。
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.
您是否查看过 BackgroundWorker 类?
它使您可以选择触发“进度更改”事件。
Did you take a look at the BackgroundWorker class?
It gives you the option to fire 'progress changed' events.
再创建一个线程。在它的线程过程中,执行以下操作:
编辑:
您可以从 Thread 派生并实现所需的事件并封装使用它。
Create one more thread. In the thread procedure for it, do:
EDIT:
You can derive from
Thread
and implement your needed event and use it encapsulated.也许是这样的:
Maybe something like this: