Home » VB.NetRSS

Cross-thread operation not valid

I know there is a few threads on this, but they all said that there is a whole bunch of problems and solutions that it could be as well as it is very hard to forget.  On reading that, I have a feeling that this is the end of my program and it can not be used.

This is the exact error that I get.
InvalidOperationExpseption was unhandled by user code.
Cross-thread operation not valid: Control 'VideoProfileDropDown' accessed from a thread other than the thread it was created on.

And here is the code.  It is pretty long.  I think the only public variable that is used is fps.

Dim CheckLoop
    Dim TextFileWriterLoop
    Dim BAdapt
    Dim MeAlgorhithim
    Dim SubME
    Dim Trellis
    Dim test = 0
    Dim VideoMode
    CheckLoop = 0
    TextFileWriterLoop = 0
    BAdapt = ""
    MeAlgorhithim = ""
    SubME = ""
    Trellis = ""
    VideoMode = ""Call CheckFolders()
    DoIf VideoInputBox.Text = ""And VideoOutputBox.Text = ""Then
        MsgBox("There are no input and output files to encode. Please enter them in.", vbExclamation + vbOKOnly, _
            "No input and output files")
        CheckLoop = CheckLoop + 1
        If CheckLoop >= 1 ThenExitDoElseIf VideoInputBox.Text = ""Then
        MsgBox("There is not input file. Please enter it in then continue.", vbExclamation + vbOKOnly, "No input file")
        CheckLoop = CheckLoop + 1
        If CheckLoop >= 1 ThenExitDoElseIf VideoOutputBox.Text = ""Then
        MsgBox("There is no output file. Please enter it in then continue.", vbExclamation + vbOKOnly, "No output file")
        CheckLoop = CheckLoop + 1
        If CheckLoop >= 1 ThenExitDoEndIf
      CheckLoop = CheckLoop + 1
    LoopUntil CheckLoop >= 1
    'DoIf VideoInputBox.Text <> ""And VideoOutputBox.Text <> ""ThenIf fps = ""ThenDim QuestionFrameRate
        QuestionFrameRate = MsgBox("There is no frame rate specified. Would you like to specify it?", vbQuestion + _
               vbYesNo, "No fps specified")
        If QuestionFrameRate = vbYes ThenMe.Enabled = FalseDim f2 AsNew Form2()
          f2.ShowDialog()
          fps = f2.Needfps()
          Me.Enabled = TrueElseIf QuestionFrameRate = vbNo Then'TextFileWriterLoop = TextFileWriterLoop + 1'If TextFileWriterLoop >= 1 Then Exit Do
          test = 1
        EndIfEndIfIf VideoBAdaptDropDown.Text = "0 - Off"Then
        BAdapt = "--b-adapt 0"ElseIf VideoBAdaptDropDown.Text = "1 - Fast"Then
        BAdapt = "--b-adapt 1"ElseIf VideoBAdaptDropDown.Text = "2 - Optimal"Then
        BAdapt = "--b-adapt 2"EndIfIf VideoMEAlgorhithimDropDown.Text = "Diamond"Then
        MeAlgorhithim = "--me dia"ElseIf VideoMEAlgorhithimDropDown.Text = "Hexagon"Then
        MeAlgorhithim = "--me hex"ElseIf VideoMEAlgorhithimDropDown.Text = "Multi Hexagon"Then
        MeAlgorhithim = "--me umh"ElseIf VideoMEAlgorhithimDropDown.Text = "Exhaustive"Then
        MeAlgorhithim = "--me esa"ElseIf VideoMEAlgorhithimDropDown.Text = "SATD Exhaustive"Then
        MeAlgorhithim = "--me tesa"EndIfIf VideoSubpixelDropDown.Text = "0 - Fullpel Only (Not Recomended)"Then
        SubME = "--subme 0"ElseIf VideoSubpixelDropDown.Text = "1 - QPel SAD"Then
        SubME = "--subme 1"ElseIf VideoSubpixelDropDown.Text = "2 - QPel SATD"Then
        SubME = "--subme 2"ElseIf VideoSubpixelDropDown.Text = "3 - HPel on MB then QPel"Then
        SubME = "--subme 3"ElseIf VideoSubpixelDropDown.Text = "4 - Always QPel"Then
        SubME = "--subme 4"ElseIf VideoSubpixelDropDown.Text = "5 - QPel & Bidir ME"Then
        SubME = "--subme 5"ElseIf VideoSubpixelDropDown.Text = "6 - RD on I/P Frames"Then
        SubME = "--subme 6"ElseIf VideoSubpixelDropDown.Text = "7 - RD on all Frames"Then
        SubME = "--subme 7"ElseIf VideoSubpixelDropDown.Text = "8 - RD reminement on I/P Frames"Then
        SubME = "--subme 8"ElseIf VideoSubpixelDropDown.Text = "9 - RD reminement on all Frames"Then
        SubME = "--subme 9"ElseIf VideoSubpixelDropDown.Text = "10 - QP-RD"Then
        SubME = "--subme 10"EndIfIf VideoTrellisDropDown.Text = "0 - None"Then
        Trellis = "--trellis 0"ElseIf VideoTrellisDropDown.Text = "1 - Final MB"Then
        Trellis = "--trellis 1"ElseIf VideoTrellisDropDown.Text = "2 - Always"Then
        Trellis = "--trellis 2"EndIfIf VideoModeDropDown.Text = "Average Bitrate"Then
        VideoMode = "AverageBitrate"ElseIf VideoModeDropDown.Text = "Two Pass - First Pass"Then
        VideoMode = "TwoOnePass"ElseIf VideoModeDropDown.Text = "Two Pass - Second Pass"Then
        VideoMode = "TwoTwoPass"ElseIf VideoModeDropDown.Text = "Constant Quality"Then
        VideoMode = "ConstantQuality"EndIfEndIfIf test = 0 ThenIf VideoMode = "ConstantQuality"ThenDim s = Sub()
              Form3.Show()
              Using p AsNew Process
                AddHandler p.ErrorDataReceived,
                  Sub(sendingProcess AsObject,
                    outLine As DataReceivedEventArgs)
                    If outLine.Data <> ""Then BeginInvoke(Sub() Form3.Label1.Text = outLine.Data.Substring(1).Split("]")(0))
                    If ProgressETACheck < 1 ThenIf outLine.Data <> ""Then BeginInvoke(Sub() ProgressETA = outLine.Data.Split(" ")(6))
                      If ProgressETA = "kb/s,"Then
                        ProgressETACheck = ProgressETACheck + 1
                      EndIfEndIfIf ProgressETACheck = 1 ThenIf outLine.Data <> ""Then BeginInvoke(Sub() Form3.Label5.Text = "ETA:" & outLine.Data.Split(" ")(8))
                      If outLine.Data <> ""Then BeginInvoke(Sub() Form3.Label4.Text = outLine.Data.Split(" ")(5) & " KB/s")
                      If outLine.Data <> ""Then BeginInvoke(Sub() Form3.Label2.Text = outLine.Data.Split(" ")(1) & " Frames")
                      If outLine.Data <> ""Then BeginInvoke(Sub() Form3.Label3.Text = outLine.Data.Split(" ")(3) & " fps")
                    EndIfEndSub

                p.StartInfo.FileName = WorkingDirectory & "\Tools\x264\x264.exe"
                p.StartInfo.Arguments = "--profile " & VideoProfileDropDown.Text _
                  & " --level " & VideoLevelDropDown.Text & _
                  " --preset medium --no-dct-decimate --no-fast-pskip --crf " & _
                  VideoCrfUpDown.Text & " " & Trellis & " " & SubME & " " & MeAlgorhithim & " " & _
                  BAdapt & " --merange " & VideoMERangeUpDown.Text & " --fps " & fps & " --ref " _
                  & VideoReferenceFramesUpDown.Text & " --bframes " & VideoBFramesUpDown.Text & " --deblock " _
                  & VideoDeblockStrengthUpDown.Text & ":" & VideoDeblockThresholdUpDown.Text & " --scenecut " _
                  & VideoIFramesUpDown.Text & " --slices " & VideoSlicesUpDown.Text & " --rc-lookahead " _
                  & VideoLookaheadUpDown.Text & " --qpmin " & VideoQuantinizersMinUpDown.Text & " --qpmax " _
                  & VideoQuantinizersMaxUpDown.Text & " --qpstep " & VideoQuantinizersStepUpDown.Text _
                  & " --output """ & VideoOutputBox.Text & """ """ & VideoInputBox.Text & """"""
                p.StartInfo.UseShellExecute = False
                p.StartInfo.RedirectStandardError = True
                p.StartInfo.CreateNoWindow = True
                p.Start()
                p.BeginErrorReadLine()
                p.WaitForExit()
              EndUsingEndSub
        s.BeginInvoke(Nothing, Nothing)
      EndIfEndIfEndSub

The error gets highlighted at the part where it says "p.StartInfo.Arguments"

Any ideas on what is wrong and what to do?

 

7 Answers Found

 

Answer 1

 

You should be able to create a function that returns the Text property

then using "Invoke" to run this method on the right thread

 

Answer 2

Why didn't you identify the line of code  that throws the error?

You cannot reference Wndows Forms or their Controls from a background thread.  You are only allowed to reference them from the thread  that declared and instantiated them.  That means that the same thread must declare and instantiate the forms and control  instances.  This thread must also have a message pump associated with it for events, which means that the Thread.ApartmentState must be STAThread. 

That is what the error  message is trying to convey to you.

 

Answer 3

I don't get it.  So what am I suppose to do?
 

Answer 4

I don't get it.  So what am I suppose to do?


Okay.  Can you tell us which line of code  that throws the error?

The message is quite clear.  Look up the BackgroundWorker class in the MSDN library.  It is far easier to use, and is designed for use with WinForms apps.  Calling Invoke might be confusing for you at this point.

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(VS.80).aspx

http://msdn.microsoft.com/en-us/library/ms228963(VS.80).aspx  APM Overview

How to: Make Thread-Safe Calls to Windows Forms Controls 

 

Answer 5

 

If I understand your problem is here

 p.StartInfo.Arguments = "--profile " & VideoProfileDropDown.Text _
     & " --level " & VideoLevelDropDown.Text & _
     " --preset medium  --no-dct-decimate --no-fast-pskip --crf " & _
     VideoCrfUpDown.Text & " " & Trellis & " " & SubME & " " & MeAlgorhithim & " " & _
     BAdapt & " --merange " & VideoMERangeUpDown.Text & " --fps "fps  & " --ref " _
     & VideoReferenceFramesUpDown.Text & " --bframes " & VideoBFramesUpDown.Text & " --deblock "

the problem is that you are accessing the controls with a wrong  thread.

To access the control, first create a function that returns the property and a delegate to this function

like this

DelegateFunction GetTextDelegate(ByVal C As Control) AsStringPrivateFunction GetText(ByVal C As Control) AsStringReturn C.Text
 EndFunction

and then, instead of

VideoProfileDropDown.Text

Use

 VideoProfileDropDown.Invoke(New GetTextDelegate(AddressOf GetText), VideoProfileDropDown).ToString

and

VideoLevelDropDown.Invoke(New GetTextDelegate(AddressOf GetText), VideoLevelDropDown).ToString
And do the same for all the controls in your statement

 

 

Answer 6

Thanks that helped.  But now when the third form opens, it wont display anything.  It just stays there until when ever.  I have not yet let it finish encoding a video because it will not display anything.  When I put my mouse cursor over it is just goes to the hour glass.  What can I do so that form will be active again?  It is suppose to display the STDOUT of x264 and have a progress bar.
 

Answer 7

Hello Metroidn1f,

Welcome to MSDN forum.

Based on my understanding, you have stated two problems  in one thread. Could you please mark the helpful replies as answer for your first question and then open a new thread  for new question?

You will get better support for that new question because more community members will focus on it. This will make answer searching in the forum easier and be beneficial to other community members as well. And this forum's policy is "one thread for one question". Thanks for your understanding.

Best regards,
Liliane
MSDN Subscriber Support in Forum
If you have any feedback on our support, please contact msdnmg@microsoft.com

 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter