Click here to Skip to main content
15,884,353 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

I am explaining what I'm trying to do. On button click I call an event btnSubmit_Click, on that I want to do 2 process at the same time one is calling a function of ThreadLogin and second is moving my ui without to hang it. But in ThreadLogin, I call a function which lie in Helper class which return bool value and take some parameter too. Below is my code :-

My Code Is :-
C#
private void ThreadLogin()
{
    bool status = false;

    Dispatcher.BeginInvoke(
new ThreadStart(() => status = Helper.login(txtName.Text, txtLogin.Text)));

    if (status)
    {
        MessageBox.Show("Login Successfully", "Success");
        btnReset_Click(null, null);
    }
    else
    {
        MessageBox.Show("The Required Data Is Not Correct", "Error");
    }
}

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
    ThreadStart tsLogin = new ThreadStart(ThreadLogin);
    Thread thLogin = new Thread(tsLogin);

    thLogin.Start();

    loading.Visibility = Visibility.Visible;

}

And I'm getting Error : The calling thread cannot access this object because a different thread owns it on hover txtName.Text and txtLogin.Text
in
C#
Dispatcher.BeginInvoke(
        new ThreadStart(() => status = Helper.login(txtName.Text, txtLogin.Text)));
Posted
Updated 8-Feb-15 8:42am
v3
Comments
Sergey Alexandrovich Kryukov 8-Feb-15 14:37pm    
Sorry for my confusion caused by your "new ThreadStart" which makes the impression that you do something with new thread in the invoked delegate. Use new Action<>(...) instead. Why BeginInvoke and not Invoke?
The idea to create a new thread on click is not good (but can work); you could better create one "permanent" thread in the very beginning and keep it waiting until you have a task and throttle it. Or use a thread pool.

You really should work with many objects in the same thread; it's not clear which one. Use just the general principles.

—SA
Kuthuparakkal 8-Feb-15 15:08pm    
Create Property (get;set) for txtName text and txtLogin text. Refer to this properties while calling the thread rather than referring to form controls.
Set the properties in the button click (submit) event.

1 solution

You cannot access the form controls from the new Thread, you need
ParameterizedThreadStart

and when accessing the controls you must check for InvokeRequired

or, as MSDN recommends, use
C#
BackgroundWorker
which handles this issue of thread access for you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900