我是一个普通的C#开发人员,但偶尔也会用Java语言开发应用程序。我想知道有没有C#的async/await等价物?简而言之,java的等价物是什么:
async Task<int> AccessTheWebAsync()
{
HttpClient client = new HttpClient();
var urlContents = await client.GetStringAsync("http://msdn.microsoft.com");
return urlContents.Length;
}
发布于 2016-08-17 00:29:44
查看ea-async,它可以很好地模拟异步/等待。根据他们的自述文件:“这在很大程度上受到了.NET CLR上异步等待的启发。”
发布于 2015-11-26 20:29:29
正如前面提到的,没有直接的等价物,但可以使用Java字节码修改创建非常接近的值(对于async/await-like指令和底层的continuations实现)。
我现在正在做一个在JavaFlow continuation库上实现异步/等待的项目,请检查https://github.com/vsilaev/java-async-await
还没有创建Maven mojo,但是您可以使用提供的Java代理运行示例。下面是异步/等待代码的样子:
public class AsyncAwaitNioFileChannelDemo {
public static void main(final String[] argv) throws Exception {
...
final AsyncAwaitNioFileChannelDemo demo = new AsyncAwaitNioFileChannelDemo();
final CompletionStage<String> result = demo.processFile("./.project");
System.out.println("Returned to caller " + LocalTime.now());
...
}
public @async CompletionStage<String> processFile(final String fileName) throws IOException {
final Path path = Paths.get(new File(fileName).toURI());
try (
final AsyncFileChannel file = new AsyncFileChannel(
path, Collections.singleton(StandardOpenOption.READ), null
);
final FileLock lock = await(file.lockAll(true))
) {
System.out.println("In process, shared lock: " + lock);
final ByteBuffer buffer = ByteBuffer.allocateDirect((int)file.size());
await( file.read(buffer, 0L) );
System.out.println("In process, bytes read: " + buffer);
buffer.rewind();
final String result = processBytes(buffer);
return asyncResult(result);
} catch (final IOException ex) {
ex.printStackTrace(System.out);
throw ex;
}
}
@async是将一个方法标记为可异步执行的注释,await()是一个使用延续等待CompletableFuture的函数,对“asyncResult asyncResult(someValue)”的调用是完成相关的CompletableFuture/Continuation
与C#一样,控制流被保留,异常处理可以以常规方式完成(像顺序执行的代码中的try/catch一样)
发布于 2013-05-14 18:01:36
Java本身没有等同的功能,但是存在提供类似功能的第三方库,例如Kilim。
https://stackoverflow.com/questions/16539245
复制相似问题