简体   繁体   English

从普通方法调用异步方法 c#

[英]Call async Method from a normal method c#

I am trying to call an async method from a normal method.我正在尝试从普通方法调用异步方法。 I have the following two issues here:我在这里有以下两个问题:

  1. When I use Task.Run in class A to class B's method, JQuery is not receiving the call.当我在 A 类中使用Task.Run到 B 类的方法时,JQuery 没有收到调用。
  2. I cannot use await because it throws this error:我无法使用await因为它会引发此错误:

    The await can only be used in an async method await 只能在异步方法中使用

I am not sure what the issue is with respect to the first problem I am having.我不确定我遇到的第一个问题是什么问题。 Secondly, is there a way to use await when calling classB because it seems to work when I made a call from a different method that is async.其次,有没有办法在调用 classB 时使用await ,因为当我从不同的异步方法进行调用时它似乎可以工作。

    public class A :IA
    {
        public A ()
    {
        consumer.Received += Received;
    }
        public void Received(object sender, BasicDeliverEventArgs ea)
        { 
           //get message here and send to classB 
            Task.Run(() => classB.PingMesssage(Message));
        }
    }


    public class B 
    {

       public async Task PingMesssage(string message)
        {
             await InvokeClientMethodToAllAsync("callJQueryMethod", "message"); //calling js here
        }
    }

You can make Received async and await a call to PingMessage :您可以使Received异步并等待对PingMessage的调用:

public async void Received(object sender, BasicDeliverEventArgs ea) {
    await classB.PingMessage(message);
}

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

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