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 215401
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T18:28:01+00:00 2026-05-11T18:28:01+00:00

I have a simple question, but I’m about 80% sure that the answer to

  • 0

I have a simple question, but I’m about 80% sure that the answer to the question will be accompanied by “you’re doing it wrong,” so I’m going to ask the not-simple question too.

The simple question: I have a public method of a public class. I want it to throw an exception if it’s called on the UI thread. How can I do this?

The much-less-simple question is: is there an easier way to refactor this design?

Background:

I’ve developed a desktop program that interoperates with a legacy application via its API. The API is not remotely thread-safe. I’ve built a class library that encapsulates interoperation with the API (which involves marshalling and unmarshalling data in an enormous byte[] buffer and then calling an external function loaded from a DLL) so that as many implementation details of the legacy API are hidden from my code as possible. Because I knew that making multiple instances of the core API object would be a catastrophe, I implemented it as a static class.

I’ve also built a set of classes for running tasks in the background of my app. The TaskManager maintains a queue of Task objects and runs them using a BackgroundWorker. Using a background thread allows the desktop app’s UI to remain responsive while interoperation with the turgid legacy app is going on; using a queue insures that only one task is calling the API at any given time.

Unfortunately, I never thought to build certain safeguards into this design. I’ve recently discovered places in the code where I was directly calling the API on the UI thread. I believe I’ve fixed all of them, but I’d like to guarantee I don’t do this again.

If I’d designed this properly from the beginning, I’d have made the API wrapper class non-static, hidden its constructor from everything except the TaskManager, and then passed the instance of the API class to each Task when it gets created. Any method the Task called that talked to the API would need to be passed the API object. This would make it impossible to use the API on the foreground thread.

The thing is, there’s a lot of code that talks to the API. Implementing this change (which I think is ultimately the right thing to do) will touch all of it. So in the meantime, I’d like to modify the API’s Call method so that it throws an exception if it’s being called on the foreground thread.

I know I’m solving the wrong problem. I can feel it in my bones. But I’m also pretty wrapped up in it right now and can’t quite see the right solution.

Edit:

I clearly framed the question the wrong way, which is why it was hard to answer. I shouldn’t be asking “How can this method know if it is running on the UI thread?” The real question is: “How can this method know if it is running on the wrong thread?” There could (in theory) be a thousand threads running. As JaredPar points out, there could be more than one UI thread. Only one thread is the right thread, and its thread ID is easy to find.

In fact, even after I refactor this code so that it’s properly designed (which I mostly did today), it’ll be worth having a mechanism in the API that checks to make sure it’s being run on the appropriate thread.

  • 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-05-11T18:28:01+00:00Added an answer on May 11, 2026 at 6:28 pm

    Part of the problem with determining if you’re on the UI thread or not is that there can be more than one UI thread. In WPF and WinForms it’s quite possible to create more than one thread for displaying UI.

    In this case though, it sounds like you have a fairly constrained scenario. The best bet is to record the Id of the UI thread or background thread in a shared location and then use Thread.CurrentThread.ManagedThreadId to ensure you’re on the correct thread.

    public class ThreadUtil {
      public static int UIThreadId;
    
      public static void EnsureNotUIThread() {
        if ( Thread.CurrentThread.ManagedThreadId == UIThreadId ) {
          throw new InvalidOperationException("Bad thread");
        }
      }
    }
    

    This approach has a couple of caveats. You must set the UIThreadId in a atomic manner and must do so before any background code runs. The best way is to probably add the following lines to your program startup

    Interlocked.Exchange(ref ThreadUtil.UIThreadID, Thread.CurrentThread.ManagedThreadId);
    

    Another trick is to look for a SynchronizationContext. Both WinForms and WPF will setup a SynchronizationContext on their UI threads in order to allow communication with background threads. For a background created and controlled by your program (i really want to stress that point) there will not be a SynchronizationContext installed unless you actually install one. So the following code can be used in that very limited circumstance

    public static bool IsBackground() { 
      return null == SynchronizationContext.Current;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 235k
  • Answers 235k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I don't think there is anything wrong with threadlocals -… May 13, 2026 at 6:05 am
  • Editorial Team
    Editorial Team added an answer i've written this test - seems to work. works with… May 13, 2026 at 6:05 am
  • Editorial Team
    Editorial Team added an answer You are looking for CHAR_LENGTH() to get the number of… May 13, 2026 at 6:05 am

Related Questions

I have a simple question, but I'm about 80% sure that the answer to
Okay this may be a simple question but I have yet to come with
I know this is a simple question for someone out there, but I have
I have a very simple question. I'd like to use a where clause after
I have a simple question to ask. I have a UTF 16 text file

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.