加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在应用程序中等待事件

发布时间:2020-12-15 22:29:48 所属栏目:百科 来源:网络整理
导读:我想在C#Project中获取数据时等待Event. 当程序读取一些数据时GetData其他程序在读取此数据结束时创建一个事件(调用EventForGetData). 所以,我需要等待完成读取的EventForGetData. 我为此任务编写了此代码,但相信此代码可能会写得更优. public static bool W
我想在C#Project中获取数据时等待Event.

当程序读取一些数据时GetData其他程序在读取此数据结束时创建一个事件(调用EventForGetData).
所以,我需要等待完成读取的EventForGetData.

我为此任务编写了此代码,但相信此代码可能会写得更优.

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;
       }

解决方法

尝试使用任务第一个任务是获取您的数据,最后进行处理或启动您的活动:

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

注意:您将放在ContinueWith中的代码将在您在StartNew中编写的代码之后执行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读