简体   繁体   English

如何在MVC C#中继续第二个方法之前等待第一个异步await方法?

[英]How to wait for first async await method before continuing second method in mvc c#?

I created two method in mvc c# using async task await for first action method I use following code 我在mvc c#中使用异步 任务创建了两个方法, 等待第一个操作方法,我使用以下代码

Thread sendData = new Thread(async () => await SaveCustomerDataAsync(DocumentID, DocumentType, bytes, fileName));
sendData.Start();

Now on my submit click this method runs in background and take some time to save in database with flag set to 1 on other-hand for next page which is kind of form submit I again use 现在,在我的提交上,单击此方法在后台运行,并花一些时间保存到数据库中,另一面的标志设置为1,用于下一页,这是我再次使用的一种提交形式

int Flag = await repository.GetFlagStatus(DocumentID);

and for getting flag status form database table I use 并用于获取标志状态表数据库表

public int GetFlagStatus(string documentID)
        {          
            var obj = (from a in db.StdPortals
                             select new StdPortalsVM
                             {
                                 DocumentID = a.DocumentID,
                                 Flag = a.Flag,
                             }).Where(x => x.DocumentID == documentID).FirstOrDefault();
          var  result = Convert.ToInt32(obj.Flag);
            return result;
        }

Now my question is that how to wait for second method until my first method save data in database as flag 0 or flag 1 according to out put of first method. 现在我的问题是,如何根据我第一个方法的输出结果等待第二个方法,直到我的第一个方法将数据保存到数据库中作为标志0或标志1。 I used await Task.Delay(10000); 我用了await Task.Delay(10000); to await second method but why should i wait for 10s if data save in database before 10s user will wait for it. 等待第二种方法,但是为什么我要等10秒钟,如果数据在10秒钟之前保存在数据库中,用户将等待它。

So, to remove that part I use timer to check database table row update after 5 sec and I modify my code like this 因此,要删除该部分,我使用计时器在5秒钟后检查数据库表行更新,并像这样修改我的代码

System.Threading.Timer Timer;
        System.DateTime StopTime;       
        public void Run(string documentId)
        {
            StopTime = System.DateTime.Now.AddMinutes(2);
            Timer = new System.Threading.Timer(TimerCallback, documentId, 0, 5000);      
        }
        private void TimerCallback(object state)
        {           
            if (System.DateTime.Now >= StopTime)
            {
                Timer.Dispose();
                return;              
            }
            else
            {
               var obj = (from a in db.StdPortals
                             select new StdPortalsVM
                             {
                                 DocumentID = a.DocumentID,
                                 Flag = a.Flag,
                             }).Where(x => x.DocumentID == documentID).FirstOrDefault();          
                if (obj != null)
                {
                    Timer.Dispose();
                    return;
                }
            }           
        }

So for this I am getting following error I also use this method to check table but getting same error. 因此,为此,我遇到以下错误,我也使用此方法检查表,但得到相同的错误。

bool obj = db.StdPortals.Any(u => u.DocumentID == state.ToString())

System.InvalidOperationException: 'The context cannot be used while the model is being created. System.InvalidOperationException:'在创建模型时不能使用上下文。 This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. 如果在OnModelCreating方法内部使用上下文,或者多个线程同时访问同一上下文实例,则可能引发此异常。 Note that instance members of DbContext and related classes are not guaranteed to be thread safe.' 注意,不能保证DbContext的实例成员和相关类是线程安全的。

I hope you understand my queries that how to wait in async task or how to check database after 5 second. 我希望您能理解我的查询,即如何在异步任务中等待或如何在5秒后检查数据库。 Thanks in advance. 提前致谢。

Thread sendData = new Thread(async () => await SaveCustomerDataAsync(DocumentID, DocumentType, bytes, fileName)); 线程sendData = new Thread(async()=>等待SaveCustomerDataAsync(DocumentID,DocumentType,字节,fileName)); sendData.Start(); sendData.Start();

You shouldn't use Thread in modern code; 您不应该在现代代码中使用Thread the only remaining use case for Thread is COM interop, which you're not doing here. Thread剩下的唯一用例是COM interop,您在这里不做。 Use Task instead: 改用Task

Task sendData = Task.Run(async () => await SaveCustomerDataAsync(DocumentID, DocumentType, bytes, fileName));

In addition to being smaller code, the Task has much nicer ways to detect completion and exceptions. 除了使用较小的代码外, Task还提供了更好的检测完成和异常的方法。

For example, if you want to asynchronously wait for sendData to complete, you can just await it: 例如,如果要异步等待sendData完成,则可以await它:

await sendData;
// SaveCustomerDataAsync has completed now.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM