askeet
askeet

Reputation: 719

Wait Event in Application

I want to wait for Event when I get data in my C# Project.

When program read some data GetData other program creates an event at the end of read this data (call EventForGetData). So, I need to wait for EventForGetData that finish read.

I wrote this code for this task but believe this code might 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;
       }

Upvotes: 4

Views: 448

Answers (1)

Badro Niaimi
Badro Niaimi

Reputation: 957

Try to use Task the first Task is to get your data, at the end do your processing or launch 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 will put inside the ContinueWith will be executed after the code that you write in the StartNew.

Upvotes: 1

Related Questions