c# - Manage tasks progressions in one user interface -


i have application in witch user can start tasks, heavy tasks. , want manage progression of these tasks in 1 user interface grid (each row task, progression bar) user can show grid clicking button (using main thread). problem have cross thread operation. know why: whenever task progression changed (with thread1), algorithm try update grid datasource (with main thread). don't know how fix it.

the datasource property of grid set bindinglist<backgroundoperation>.

the definition of task (backgroundoperation)

public class backgroundoperation {     public int progression;     public int progression     {         { return progression;}         set         {             progression = value;             onpropertychanged("progression");         }     }      public event eventhandler onrun;     public event eventhandler<progresschangedeventargs> onprogresschanged;     public event propertychangedeventhandler propertychanged;      public void run()     {         var task = new task(() =>         {             if (onrun != null)                 onrun(this, null);         });      task.start();     }      public void reportprogress(int progression)     {         progression = progression;          if (onprogresschanged != null)             onprogresschanged(this, new progresschangedeventargs { progression = progression });     }       protected void onpropertychanged(string name)     {         propertychangedeventhandler handler = propertychanged;         if (handler != null)         {             handler(this, new propertychangedeventargs(name));         }     } } 

you need run onprogresschanged (which btw should called progresschanged) on ui thread. can saving the current synchronizationcontext when class created , post()ing delegate there:

public class backgroundoperation {     private readonly synchronizationcontext m_synchronizationcontext;      public backgroundoperation()     {         m_synchronizationcontext = synchronizationcontext.current;     }      …      public void reportprogress(int progression)     {         progression = progression;          var handler = onprogresschanged;         if (handler != null)             m_synchronizationcontext.post(                 _ => handler(                     this,                     new progresschangedeventargs { progression = progression }),                 null);     } } 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -