首页 \ 问答 \ 如何知道我的异步方法正在等待?(How to know my async method is being awaited?)

如何知道我的异步方法正在等待?(How to know my async method is being awaited?)

是否可以知道我的方法是否使用'await'关键字进行调用?

例如; 方法MyAsync()想知道是否等待它。

public void CallForBackground()
{
    MyAsync();
}

public async void CallAsync()
{
    bool result = await MyAsync();
}

public Task<bool> MyAsync()
{
    return Task.Run(() =>
    {
    //do something endlessly if its being called without 'await', but how do I know the caller is 'await'ing or not?
    //do something only once if its being called with 'await', but how do I know the caller is 'await'ing or not?


    return true;
    });
}

编辑:添加了一个场景,我想知道是否使用'await'调用MyAsync();

1)假设MyAsync()使用TCP连接到远程服务器。

2)MyAsync()是异步的并且是等待的。

3)假设UserA想要异步连接到远程服务器,一旦完成,他/她想要在继续​​他的过程之前知道它是否成功。 类似于CallAsync()方法实现的东西。

4)UserB想要触发MyAsync()方法,而不是等待它完成。 在这种情况下,UserB在向远程服务器发送消息之前不关心它是否已连接。 类似于CallForBackground()方法实现的东西。

因此,对于UserA(等待),MyAsync()方法将尝试一次并返回状态。 但对于UserB(不等待),方法将继续尝试。 对于这个逻辑,MyAsync()需要知道它是否正在等待。 我们如何实现这一目标?


Is it possible to know that my method is being called using 'await' keyword or not?

For example; method MyAsync() would like to know whether its being awaited or not.

public void CallForBackground()
{
    MyAsync();
}

public async void CallAsync()
{
    bool result = await MyAsync();
}

public Task<bool> MyAsync()
{
    return Task.Run(() =>
    {
    //do something endlessly if its being called without 'await', but how do I know the caller is 'await'ing or not?
    //do something only once if its being called with 'await', but how do I know the caller is 'await'ing or not?


    return true;
    });
}

EDITED: Added a scenario where I would like to know whether MyAsync() is being called with or without 'await';

1) Let's say MyAsync() is connecting to a remote server using TCP.

2) MyAsync() is asynchronous and awaitable.

3) Let's say UserA wanted to connect to remote server asynchronously and once completed he/she would like to know whether it was successful or not before continuing his process. Something similar to CallAsync() method implementation.

4) And UserB wants to fire MyAsync() method, without waiting for it to complete. In this case, UserB don't care whether it was connected or not until he sends a message to remote server. Something similar to CallForBackground() method implementation.

So for UserA (awaiting) MyAsync() method will attempt once and return the status. But for UserB (not awaiting), method will keep trying. For this logic, MyAsync() needs to know whether its being awaiting or not. How do we achieve this?


原文:https://stackoverflow.com/questions/23976247
更新时间:2019-12-03 08:12

最满意答案

我们如何实现这一目标?

你不*。 根据用户对其返回值的作用,方法的行为不应该有所不同。 如果您想要有两种不同的行为,请在方法中添加bool参数,或者更好的是,为此设置两种不同的方法。


*实际上有一种方法await你的方法是否await 。 但它很复杂(它涉及使用自定义等待者而不是Task ),我不认为这是正确的解决方案。


How do we achieve this?

You don't*. A method shouldn't behave differently depending on what the user does to its return value. If you want to have two different behaviors, either add a bool parameter to your method, or, even better, have two separate methods for this.


* Actually there is a way to find out whether your method was awaited. But it's quite complicated (it involves using custom awaiters instead of Task) and I don't think it's the right solution here.

2014-06-01

相关问答

更多

React-Router v4嵌套路由不匹配(React-Router v4 Nested Route Not Matching)

从父路径中删除exact删除。 如果您只是内联编写内容,很容易看出发生了什么: <Route exact path="/foo" component={props => { // this component will only load if the url is *exactly* /foo // it doesn't matter if you have nested routes in here or not // because they will never be ren

Bootstrap表单助手时间选择器不能在我的手机上工作(Bootstrap form helper time picker not working on my mobile phone)

正如评论中所述,似乎很少有人使用这个插件。 我最终使用https://github.com/Eonasdan/bootstrap-datetimepicker 。 As stated in the comments, there seems to be little support using this plugin. I ended up using https://github.com/Eonasdan/bootstrap-datetimepicker instead.

将Android Fragments置于其初始状态(Bringing back Android Fragments in its initial state)

当你用片段a替换片段c时,创建一个新的片段实例getSupportFragmentManager()。beginTransaction()。replace(R.id.llContainer,new FragmentA())。commit(); When I did a "getActivity().findViewById(R.id.userid));" from fragment B, it was picking up the previous value, but if I do a "g

根据用户输入创建大量数字(Creating a number of figures dependent on user input)

看看这是否适合你: Data = rand(40,30); %// Just a small data set for testing. %// Ask user how many figures are desired prompt = {'Enter desired number of figures:'}; dlg_title = 'Input'; num_lines = 1; def = {'5'}; NumFigures = inputdlg(prompt,dlg_title,nu

从c ++中的类向量调用函数(call functions from vector of class in c++)

它应该是sorting s; 而不是vector<sorting> 。 您定义了在类sorting定义的read() amd sortt()方法。 It should be sorting s; and not vector<sorting>. You defined those methods read() amd sortt() defined in the class sorting.

string.split中的Java outOfMemory异常(Java outOfMemory exception in string.split)

您应该首先尝试将文件缩小到足够小以使其正常工作。 这将允许您评估您有多大的问题。 其次,你的问题肯定与String#split无关,因为你一次只在一行上使用它。 Vertex和Edge实例的Vertex是什么。 您将不得不重新设计一个更小的占用空间,或彻底检查您的算法,以便只能在内存中使用图形的一部分,其余部分在磁盘上。 PS只是一般的Java注释:不要写 String s1 = new String(tokens[0]); String s2 = new String(tokens[1]);

FIrefox不会阻止调度的提交事件(FIrefox doesn't preventing dispatched submit event)

首先,这不是特定于反应的问题。 如何避免这个bug? 似乎{ cancelable: true }标志阻止Firefox在这种情况下重新加载页面。 this.form.dispatchEvent(new Event('submit', { cancelable: true })) 这是一个完整而简单的例子: <!Doctype html> <html> <head> <script type="text/javascript"> document.addEventLis

为什么迭代器对象不是用Java中的列表集合的new关键字创建的(why is iterator object not created with new keyword for list collection in Java)

这是否意味着迭代器方法是静态的,它只返回一个新的可迭代对象,其中列表作为其字段。 不,这是一个实例方法。 它只返回对Iterator<String>的引用。 所以iterator()方法的主体可能包含一个new语句(尽管它可能会调用其他东西)。 让我们暂时从迭代器和泛型中取出它 - 类似的情况是: class Bar {} class Foo { Bar createBar() { return new Bar(); } } public class Test

相关文章

更多

最新问答

更多
  • 根据Woocommerce中的自定义字段计算自定义购物车商品价格(Custom cart item price calculation based on dimentions custom fields in Woocommerce)
  • 分开foreach项目并单独打印(Separate foreach items and print them individually)
  • 写模式管道是否同步?(Is write mode pipe synchronous?)
  • 发现可用的Windows Phone强调色和本地化名称(Discover available Windows Phone accent colors and localized names)
  • 使用多线程和WPF更新集合(Update Collection with multithreading and WPF)
  • 如何在字符串的情况下使用同步?(How should the synchronization be used in case of strings?)
  • 打印唯一的行,比较不超过N个字符(Print unique lines, compare no more than N characters)
  • Javascript / jQuery - 如何调用switch case从另一个函数执行(Javascript/jQuery - how to call a switch case to execute from another function)
  • Hbase超时错误不断发生(Hbase timeout errors keep occuring)
  • 如何在Delphi中更改TabControl中活动TAB的颜色(How to change the color of active TAB in a TabControl, in Delphi)
  • 正则表达式:在sublime文本中替换一些PHP代码(Regex: replace some pieces of php code in sublime text)
  • 在带有Scene2D的LibGDX中,如何在按下按钮时连续向右走?(In LibGDX with Scene2D, how can I continuously walk to the right when a button is pressed?)
  • 累加器如何在Haskell中工作?(How do accumulators work in Haskell?)
  • 使用开关检查市场和前缀与正确的货币符号(using switch to check market and prefix with correct currency symbol)
  • 在哪里分配一次使用类?(Where to allocate one time use class?)
  • 如何从两个DateTime / NaiveDateTime获取持续时间?(How do I get Duration from two DateTime / NaiveDateTime?)
  • 解析TimeSpan大于24小时?(Parse a TimeSpan greater than 24 hours? [duplicate])
  • 如何在球拍中本地更改阅读规则?(How to locally change reading rules in racket?)
  • 数据库应该由DI注入时的模拟存储(通过构造函数)(Mock storage when database should be injected by DI (through constructor))
  • 使用maven集成2个eclipse项目(Integrate 2 eclipse projects using maven)
  • 角度ng-repeat不检测变化(Angular ng-repeat not detecting changes)
  • Xaml组件在Silverlight + XNA应用程序的多个页面中可见(Xaml component visible in multiple pages in Silverlight+XNA applications)
  • 如何将`var`变量等同于另一个查询(How to equate `var` variable to another query)
  • 如何设计hyperledger链代码以适合您的业务?(how to design your chaincode of hyperledger to fit for your business?)
  • PHP readfile错误(PHP readfile error)
  • 在Date之后排序列表然后是时间(Sorting list after Date then time)
  • Android内部版本号(Android build number)
  • 在没有预设退出条件的情况下停止无限循环(stopping an infinite loop with no preset exit condition)
  • Phonegap应用程序全屏通过html页面中的按钮(Phonegap Application fullscreen through a button in html page)
  • PAA是否适合在门户网站中自动执行wcm库部署和设置?(Is PAA a good candidate for automating wcm library deployment and setup in portal?)