0
votes

I am using a backgroundworker and I think there is a cross thread thing.. But I cant solve it.

my code is here

  private void bgworkerGameLoad_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        var arg = e.Argument.ToString();
        var liste = webHelper.ShowGame("http://www.abx.com/" + arg);

        txtHowToPlay.Invoke(new Action(() => txtHowToPlay.Text = String.Format("Oyun Bilgi: {0}", liste[0])));

        txtInfo.Invoke(new Action(() => txtInfo.Text = String.Format("Nasıl Oynanır: {0}", liste[1])));

       bgworkerGameLoad.ReportProgress(0,liste[2]);

    }

   private void bgworkerGameLoad_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {


        if (FlashPlayerActive)
            UnLoad();
        string url="";
        Invoke(new MethodInvoker(() =>
            {
                url= e.UserState.ToString();
            Thread.Sleep(2);
        }));

        axShockwaveFlash1.Movie = url;

        LoadFlash();

        pbWaitForChannelLoading.Visible = false;
        axShockwaveFlash1.Play();
    }

the problem is that I cant get the e.UserState.ToString() for my shocwaveplayer. I used a local string variable but its the same result.

it is occured targetofaninvocation exception in program.cs

     Application.Run(new FrmMain());;

but that code is in frmMain.cs

this is detail of the exception

System.Reflection.TargetInvocationException was unhandled Message=Exception has been thrown by the target of an invocation. Source=mscorlib StackTrace: at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Delegate.DynamicInvokeImpl(Object[] args) at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme) at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme) at System.Windows.Forms.Control.InvokeMarshaledCallbacks() at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at XXX.Program.Main() in c:\Users..............\Program.cs:line 23 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.NullReferenceException Message=Object reference not set to an instance of an object. Source=System.Windows.Forms StackTrace: at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous) at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args) at System.Windows.Forms.Control.Invoke(Delegate method) at XXX.FrmMain.bgworkerGameLoad_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e) in c:\Users..........\FrmMain.cs:line 332 at System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs e) at System.ComponentModel.BackgroundWorker.AsyncOperationCompleted(Object arg) InnerException:

what is my mistake? I tried to use delegate but its the same..

2
BgWorker runs on seperate thread than UI.So you cant access UI controls like txtHowToPlay in bg_DoWork method.Chirag Rupani
@JonSkeet, its Invoke(new MethodInvoker(() => { xx = e.UserState.ToString(); Thread.Sleep(2); }));ertan2002
@usercr, hey its not a problem. it works.. but the problem i cant access the string variable even i tried to use method invokerertan2002
You need to look at the exception's InnerException to see what went wrong. It is easier to diagnose by using Debug + Exceptions, tick the Thrown checkbox for CLR exceptions so the debugger stops when the exception is thrown. In general you are doing it wrong, there isn't anything that your DoWork event handler does that takes time so you are simply not ahead by making your code hard to write and diagnose. If you find yourself just needing to write Begin/Invoke then you know you are doing it wrong ;)Hans Passant

2 Answers

0
votes

It sounds like the problem is as simple as e.UserState being null. You don't even need to use Invoke to get at UserState - you'll see the same problem if you just have:

if (FlashPlayerActive)
    UnLoad();
string url = e.UserState.ToString();
Thread.Sleep(2); // This is generally a bad idea anyway, btw...

Where are you setting the UserState? I suspect you're not setting it anywhere, so it's still null, which is why you're getting an exception.

0
votes

I solved the problem..

I hadnt added axShockwaveFlash1 to my form before set values..

in LoadFlash function, it was

    public void LoadFlash()
    {

        axShockwaveFlash1 = new AxShockwaveFlash();
        axShockwaveFlash1.BeginInit();
        axShockwaveFlash1.Location = new Point(14, 196);
        axShockwaveFlash1.Name = "Test Movie";
        axShockwaveFlash1.TabIndex = 0;
        axShockwaveFlash1.Movie = liste[2];
        axShockwaveFlash1.EmbedMovie = true;
        axShockwaveFlash1.AutoSize = true;
        axShockwaveFlash1.Size = new Size(640, 480);

        axShockwaveFlash1.Visible = true;
        axShockwaveFlash1.EndInit();
        splitContainerControl.Panel2.Controls.Add(axShockwaveFlash1);
        FlashPlayerActive = true;

    } 

but i changed this code like

    public void LoadFlash()
    {

        axShockwaveFlash1 = new AxShockwaveFlash();

      splitContainerControl.Panel2.Controls.Add(axShockwaveFlash1);

        axShockwaveFlash1.BeginInit();
        axShockwaveFlash1.Location = new Point(14, 196);
     ...

it works..

if found the solution here

http://forum.fusioncharts.com/topic/2424-how-to-resolve-invalidactivexstateexception-while-loading-chart/#entry8855

thanx