开发者

Waiting for event. How not to freeze the gui

Hello I have following problem. I need something like "lock" to make 开发者_开发问答my program wait for an event. I have some db access based on events. So if I want to get something from db and do something on it I am writing:

void getData()
{
    ...
    ...
    getMyDataFromDbPlease();
}

void responseEvent(parameters...)
{
    //Ok i have my data, now i do something on it
    ...
    ...
}

So if I have large logic, I have to break it into two pieces. And if I want to get data 5 times in one alghoritm, i have to break it into 6 pieces.

So I want to get something like this:

void getData()
{
    ...
    ...
    getMyDataFromDbPlease();

    //somehow wait for data here

    getMyDataFromDbPlease();
    ...
    ...
}

But i want this magic waiting not to freeze my GUI. How can I achive that? I work on wpf.


You could wire up your call to the database using a background task, then dispatch the actual update back on your UI thread:

// create a background task to load data without blocking the UI
Task.Factory.StartNew(() =>
{
  var data = getData(); // call to DB or whatever

  // invoke user code on the main UI thread
  Dispatcher.Invoke(new Action(() =>
  {
    doSomethingWithData();
  }));
});


Try placing the code in a seperate thread. But don't forget that you have to use Dispatcher.Invoke() for accessing the GUI. Alternatively you can bind the GUI to a variable that is changed in the seperate thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜