✅ Using a method that is running on another thread
I am making a program that does few operations to video files. on clicking a button, an dialog box is opened in which the user has to select the video file.
Once the video gets selected in the dialog box, the operation will begin. here is where I encounter a problem.
I want to write messages as each operation is done performing or when an operation is about to perform to a listbox in my GUI app. If this was a commandline app, I can just use Console.Writeline with my message strings but in a GUI app, I can't do something similar and so I decided to use the listbox command and here is where my issue begins.
The issue is that all the messages will appear only when my program's whole video operation code is done performing and that defeats the whole point of using messages to tell the user that something is being performed when the operation is being done.
I heard that I have to multi thread my app and so decided to put my whole video related code to another thread and then use a method to call the strings from my video extraction thread. I encounter a exception with this one stating that I can't access a method which is in another thread.
Now the first message I write will be Parsing Video file.... and this message will appear once the video is selected in the dialog box and is being opened in a filestream.
My code below should show as to how I am using a method to call the messages.
12 Replies
Here is my code:
Assuming you're using WPF, you'd use
Dispatcher.Invoke
no not wpf. its winforms
You can use
BeginInvoke
Control.BeginInvoke Method (System.Windows.Forms)
Executes a delegate asynchronously on the thread that the control's underlying handle was created on.
can you tell me where exactly I have to put it in my code?
I am worried if I end up causing a thread related issue like race condition in the process.
You'd replace your calls to
Msg
method with BeginInvoke, which should then call Msg
In the example on MSFT's site
You can see BeingInvoke
is called on the TextBox and the call back DelegateMethod
is passed to itsince I don't use a textbox is it like this then:
?
No, not quite like this, you need to pass the
text
in the second parameter like this
Or you can call it as an Action without declaring a delegate
is there a way to ensure that the Button on my app is not interactable until the operation is completed ?
Set
Enabled
to falseClosed!