infinite thread c#the calling thread cannot access this object because a different thread owns it. c# in csharp

Here's an example code for creating an infinite loop using a separate thread in C#:

using System.Threading;

Thread thread = new Thread(() =>
{
    while (true)
    {
        // Do some work
    }
});

thread.Start();
134 chars
12 lines

However, if you want to update the UI from this background thread, you may encounter the "calling thread cannot access this object because a different thread owns it" exception. That's because UI controls can only be accessed from the UI thread. To fix this, you need to use the SynchronizationContext class to marshal the UI update back to the UI thread. Here's a modified code snippet that updates a label on the UI thread from the background thread:

using System.Threading;

// Get the synchronization context of the UI thread
var uiContext = SynchronizationContext.Current;

Thread thread = new Thread(() =>
{
    while (true)
    {
        // Do some work

        // Update the UI on the UI thread
        uiContext.Post(new SendOrPostCallback((_) =>
        {
            // This code runs on the UI thread
            label1.Text = "Updated on UI thread";
        }), null);

        // Sleep for some time
        Thread.Sleep(1000);
    }
});

thread.Start();
517 chars
25 lines

In this example, the SynchronizationContext.Current property is used to get the SynchronizationContext of the UI thread. Then, the Post method is used to marshal the UI update back to the UI thread.

gistlibby LogSnag