Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9177131
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T17:15:33+00:00 2026-06-17T17:15:33+00:00

I have a code like the following (I have stripped some code for readability)

  • 0

I have a code like the following (I have stripped some code for readability)

    private void RicercaArticoloStripped(object sender, DoWorkEventArgs e)
    {
        try
        {
            using (var context = new ControlloSchedeLocalEntities())
            {
                var prodotti = context.VProdotti.Where(i => i.WACMAT == textBoxCodiceArticolo.Text);

                if (prodotti.Count() > 0)
                {
                    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                    {
                        textBlockDescrizioneArticolo.Text = prodotti.FirstOrDefault().WADESC;
                    }));
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error:\n\n" + ex.Message + "\r\nStack: " + ex.ToString());
        }
    }


    private void textBoxCodiceArticolo_KeyUpStripped(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += new DoWorkEventHandler(RicercaArticoloStripped);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RicercaArticoloWorkerCompleted);
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);

            object[] parameters = new object[] { textBoxCodiceArticolo.Text, textBlockDescrizioneArticolo.Text };
            worker.RunWorkerAsync(parameters);
        }
    }

So, as for my understanding of BackgroundWorker, when I instantiate the:
var prodotti = context.VProdotti.Where(i => i.WACMAT == textBoxCodiceArticolo.Text);

I am doing it FROM the working thread, not the UI thread.

But I get an exception on the line immediately below, when I try to access the value:
if (prodotti.Count() > 0)

I get the (in)famous error:
“The calling thread cannot access this object because a different thread owns it”

Why?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T17:15:34+00:00Added an answer on June 17, 2026 at 5:15 pm

    As you already said you must use Dispatcher.BeginInvoke/Invoke to perform operations from the control’s owner thread or you will get “The calling thread cannot access this object because a different thread owns it” exception. Thats why you got this exception;

    And here is why you got this exception on the line below (when prodotti.Count() was called):

    When you create prodotti variable it’s just a IEnumerable<T> object. So he actually calculates only when you call for prodotti.Count() method and thats why you got exception on this line.

    IEnumerable actually is generator, that means that he will produce new set of objects every time he used.

    To test this you can calculate prodotti as shown bellow:

    var prodotti = context.VProdotti.Where(i => i.WACMAT == textBoxCodiceArticolo.Text).ToList();
    

    In this case you will get exception immediately because .ToList() forces all calculations.

    Check this article for generators and enumerators: http://www.codeproject.com/Articles/155462/IEnumerable-Lazy-and-Dangerous

    Updated:
    really, when you use IEnumerable with reference types you can get the same objects as previously. Read this answer for more: https://stackoverflow.com/a/14361094/1467309

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using SDL with FASM, and have code that's minimally like the following: format
In Ado.NET world, I could have code like following Void SomeMethod(bool flag) { String
If I have code like the following: public const string UNSPECIFIED_DATATYPE = 11; private
If I have a code like the following: try { doSomething(); } catch (...)
I have code that looks like the following: public void GetData(dynamic dObj) { unsafe
I have code like following: switch(sort.Column) { case code: model = (sort.Direction == SortDirection.Ascending)
I have code like the following... HANDLE event = CreateEvent(NULL, false, false, NULL); //
I have code like the following in a UserControl: Protected Overrides Sub Render(ByVal writer
I have code that looks like the following: //unrelated code snipped resolver.reset(new tcp::resolver(iosvc)); tcp::resolver::query
I have code that looks like the following: <form id=MyForm name=MyForm method=post action=index.php> <input

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.