Waiting for an event in the application

I want to wait for an event when I receive data in my C # project.

When a program reads some GetData data, another program raises an event at the end of reading that data (call EventForGetData). So, I need to wait until EventForGetData is finished.

I wrote this code for this task, but I believe that this code can write more optimal.

        public static bool WaitEvent = true;
        public void EventForGetData(string variable)
        {
            WaitEvent = false;
        }

        public static string ForWaitGetData()
        {
            WaitEvent = true;
            while (WaitEvent)
            {
                System.Threading.Thread.Sleep(5);
                Application.DoEvents();                   
            }
            return Variable;
        }

        public object GetData(){
           // start read data
              ...
           // Wait for finish to read data 
           ForWaitGetData();

         // finish read data
              ...
          return MyObject;
       }
+4
source share
1 answer

Try using the "Task", the first task is to get your data, at the end to do your processing or start your event: Example

Task task = Task.Factory.StartNew(() =>
            {
              //put you code here the first one 
            }).ContinueWith((rs) =>{
              //Launch your event or anything you want
            });

Note : the code that you put inside ContinueWith will be executed after the code you write to StartNew.

+1
source

All Articles