Dor Bracha
Dor Bracha

Reputation: 11

methods running on different threads WPF UI

I need to be thread safe on my app, how do you recommend to design the code? I want that method1 will run every 5 sec and connect to the DB, and that on OnclickButton(object sender ,event e) will connect the DB.

It goes like this:

method1()
{
    // connect db
    // do something
} 
OnclickButton(object sender,event e)
{
    // connect db
    // do something 2
}

Thanks guys

Upvotes: 0

Views: 101

Answers (1)

Vadim Martynov
Vadim Martynov

Reputation: 8892

Well, it's bit broad, but in my opinion you are need 2 options:

  1. Use MVVM pattern which is standard de facto for WPF apps. You can use on of the many MVVM libraries like MVVM light toolkit. It will help you to separate your presentation logic and business logic.
  2. Good, after first step you will have ViewModel with binded data which can updated from Model or initiate actions. Your ViewModel can get data from the Model in the async-manner and updates own properites in the UI-thread. If you are using Asynchronous Programming with Async and Await you can just continue to use your code if your methods initiates from UI thread. If you are using "old-style" asynchronous programming then you can use Dispatcher class to update bindable properties in the UI thread:

    var newUsername = model.GetUserName(); // background thread
    Application.Current.Dispatcher.BeginInvoke(
        new Action(() => this.UserName = newUsername));
    

Upvotes: 1

Related Questions