Norbert Forgacs
Norbert Forgacs

Reputation: 593

Invoking a method's result to the main thread

I am wondering about the following:

I have an observable collection named Container and method named Method.

On the main thread I want to add the returned value from Method to the Container.

The following code runs on another thread, so I have to Invoke the Container.Add to the app current thread to not have errors:

object obj = Method()
App.Current.Dispatcher.Invoke(() => {
    Container.Add((MyObject)obj)
});

My question is if I would do the following

App.Current.Dispatcher.Invoke(() => {
    Container.Add((MyObject)Method())
});

The method (which is a long running method) will run on the app current thread, which is not quite correct because it will hand the UI, could I invoke only the returned value of the method to be added to the Container without defining the object like in the first example?

Upvotes: 3

Views: 2495

Answers (2)

Clemens
Clemens

Reputation: 128013

You may use this Invoke overload:

Dispatcher.Invoke(new Action<MyObject>(o => Container.Add(o)), (MyObject)Method());

You may however get rid of the background thread and call Method in a Task. Thus you would avoid the need to call Dispatcher.Invoke:

Container.Add(await Task.Run(() => (MyObject)Method()));

Upvotes: 4

Grx70
Grx70

Reputation: 10339

Alternatively to @Clemens' proposal, you can use Task-based Asynchronous Pattern (TAP):

App.Current.Dispatcher.Invoke(async () =>
{
    Container.Add(await Task.Run(() => Method()));
});

Note though that this requires either .NET 4.5 or later, or .NET 4 together with Microsoft.Bcl.Async NuGet package.

Upvotes: 3

Related Questions