Search code examples
c#wpfui-threaduielement

I am getting/checking type of UIElement through non owning UI thread is it safe?


I have a custom UI Element. I am accessing it through a thread other than the owning thread. I am able to get/check its type (custom type) and got correct result. Is it safe to depend upon this result? (I know in order to access/update its value we have to use owning UI thread)

Ex:

bool result = ((uiElement as CustomType) != null)

Solution

  • Checking the control's type can safely be done in a thread other than the owning thread:

    bool result = uiElement is CustomType;
    

    If for any reason (you haven't mentioned in the question),

    • uiElement is an externally accessible variable (e.g. a field or a property),
    • and the value of uiElement may be changed by another thread,
    • and you still need to access it after the type check,

    it is safer to once assign the result of the type check to a local variable:

    var customElement = uiElement as CustomType;
    
    if (customElement != null)
    {
        // do something with customElement ...
    }