开发者

GDI+ draw when loading data like a map

I have an application that finds the shortest path between 2 squares, and when the path is longer or more complicate it can take 1-2 seconds to find it and I want to write on the screen a loading message that changes (first "Loading" then "Loading." then "Loading.." etc.).

Another problem is that the application give a "Not Responding" message if it take longer (10-12 seconds) how can I get rid of this?

The code so far:

Form1.cs:

namespace PathFinder
{
   Map map1;
   public Form1()
   {
      map1 = new Map(tileDimension, mapDimension);
      map1.Generate(); //the function that calcul开发者_JAVA百科ate the path
      this.Invalidate();
   }

   private void Form1_Paint(object sender, PaintEventArgs e)
   {
      //drawings
      this.Invalidate();
   }
}

Map.cs:

namespace PathFinder
{

  public Map(Point tileDim, Point mapDim)
  {
     //Initialization
  }

  public Generate()
  {
     //lots of loops
  }
}


The reason for this is that UI main thread must process events. If it does not for a period, it starts complaining, that is what you are experiencing.

So, you should not block the UI thread with any lengthy processing.

Use the BackgroundWorker Class for such operations.

Another option (not recommended) would be using

for...
{
    // ...
    // Some lengthy part of processing, but not as lengthy as the whole thing
    Application.DoEvents();
}

in-between the lengthy operation cycles, if you choose to do processing in the UI thread.


Use a BackgroundWorker to offload long-running calculations on a worker thread. That prevents the UI from freezing. BGW is well covered by the MSDN Library, be sure to follow the examples.

Any drawing you have to do however still needs to be done on the UI thread with the Paint event. Just make sure that you can do so as quickly as possible. Have the worker store the path in, say, a Point[] or a GraphicsPath. Call Invalidate() in the BGW's RunWorkerCompleted event handler to get the paint event to run.


Seeing your code might help.To avoid window to halt you may use seperate thread for calculations or in your process you may use Applications.DoEvents(); if winform. As i said.

Well Does this works?

namespace PathFinder
{
   Map map1;
 BackgroundWorker GetSomeData = new BackgroundWorker();

   public Form1()
   {
      GetSomeData .DoWork += new DoWorkEventHandler(GetSomeData_DoWork);
      map1 = new Map(tileDimension, mapDimension);
      GetSomeData.RunWorkerAsync();
      this.Invalidate();
   }
 void GetSomeData_DoWork(object sender, DoWorkEventArgs e)
 {
      map1.Generate(); //the function that calculate the path
 }

   private void Form1_Paint(object sender, PaintEventArgs e)
   {
      //drawings
      this.Invalidate();
   }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜