我刚刚阅读了有关使用 await 在 C# 5.0 中处理异步函数的新方法。和 async关键字。来自 C# reference on await 的示例:
private async Task SumPageSizesAsync()
{
// To use the HttpClient type in desktop apps, you must include a using directive and add a
// reference for the System.Net.Http namespace.
HttpClient client = new HttpClient();
// . . .
Task<byte[]> getContentsTask = client.GetByteArrayAsync(url);
byte[] urlContents = await getContentsTask;
// Equivalently, now that you see how it works, you can write the same thing in a single line.
//byte[] urlContents = await client.GetByteArrayAsync(url);
// . . .
}
A Task<byte[]>表示将生成 byte[] 类型值的异步任务的 Future .使用关键字 await在 Task 上基本上会将函数的其余部分放在任务完成时调用的延续中。任何使用 await 的函数必须使用关键字 async并输入 Task<a>如果它会返回类型 a .
所以线条
byte[] urlContents = await getContentsTask;
// Do something with urlContents
会翻译成类似的东西
Task newTask = getContentsTask.registerContinuation(
byte[] urlContents => {
// Do something with urlContents
});
return newTask;
这感觉很像 Monad(-transformer?)。感觉应该是 与 CPS monad 有一些关系,但也可能不是。
这是我尝试编写相应的 Haskell 类型
-- The monad that async functions should run in
instance Monad Async
-- The same as the the C# keyword
await :: Async (Task a) -> Async a
-- Returns the current Task, should wrap what corresponds to
-- a async method in C#.
asyncFunction :: Async a -> Async (Task a)
-- Corresponds to the method Task.Run()
taskRun :: a -> Task a
以及上面例子的粗略翻译
instance MonadIO Async -- Needed for this example
sumPageSizesAsync :: Async (Task ())
sumPageSizesAsync = asyncFunction $ do
client <- liftIO newHttpClient
-- client :: HttpClient
-- ...
getContentsTask <- getByteArrayAsync client url
-- getContentsTask :: Task [byte]
urlContents <- await getContentsTask
-- urlContents :: [byte]
-- ...
这会是 Haskell 中的相应类型吗?是否有任何 Haskell 库以这种方式(或类似方式)实现处理异步函数/操作的方式?
另外:你能用 CPS 转换器构建这个吗?
是的, Control.Concurrent.Async module 确实解决了类似的问题(并且具有类似的界面),但是以完全不同的方式进行。我猜 Control.Monad.Task 将是一个更接近的比赛。我想(我认为)我正在寻找的是 Futures 的单子(monad)界面在幕后使用 Continuation Passing Style。
最佳答案
这是一个构建在 async 库之上的 Task monad:
import Control.Concurrent.Async (async, wait)
newtype Task a = Task { fork :: IO (IO a) }
newTask :: IO a -> Task a
newTask io = Task $ do
w <- async io
return (wait w)
instance Monad Task where
return a = Task $ return (return a)
m >>= f = newTask $ do
aFut <- fork m
a <- aFut
bFut <- fork (f a)
bFut
请注意,我还没有为此检查 monad 法则,因此它可能不正确。
这就是您定义在后台运行的原始任务的方式:
import Control.Concurrent (threadDelay)
test1 :: Task Int
test1 = newTask $ do
threadDelay 1000000 -- Wait 1 second
putStrLn "Hello,"
return 1
test2 :: Task Int
test2 = newTask $ do
threadDelay 1000000
putStrLn " world!"
return 2
然后您可以使用 do 符号组合 Task,这会创建一个准备运行的新延迟任务:
test3 :: Task Int
test3 = do
n1 <- test1
n2 <- test2
return (n1 + n2)
运行 fork test3 将生成 Task 并返回一个 future ,您可以随时调用它来要求结果,必要时阻塞直到完成。
为了证明它有效,我将进行两个简单的测试。首先,我将 fork test3 而不要求它的 future ,只是为了确保它正确地生成复合线程:
main = do
fork test3
getLine -- wait without demanding the future
这可以正常工作:
$ ./task
Hello,
world!
<Enter>
$
现在我们可以测试当我们要求结果时会发生什么:
main = do
fut <- fork test3
n <- fut -- block until 'test3' is done
print n
...这也有效:
$ ./task
Hello,
world!
3
$
关于c# - Haskell 相当于 C# 5 async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20295604/
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.
Java的Collections.unmodifiableList和Collections.unmodifiableMap在Ruby标准API中是否有等价物? 最佳答案 使用freeze应用程序接口(interface):Preventsfurthermodificationstoobj.ARuntimeErrorwillberaisedifmodificationisattempted.Thereisnowaytounfreezeafrozenobject.SeealsoObject#frozen?.Thismethodretur
是否有Ruby等效于Python的方法来获取在字符串末尾结束的子字符串,如str[3:]?必须输入字符串的长度并不方便。 最佳答案 传递最后一个元素=-1的范围str[3..-1] 关于python-Ruby相当于Pythonstr[3:],我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/12978768/
我想知道,是否有一些流操作可以像ruby中的each_with_index那样做。其中each_with_index遍历值以及值的索引。 最佳答案 没有专门用于该目的的流操作。但您可以通过多种方式模仿该功能。索引变量:以下方法适用于顺序流。int[]index={0};stream.forEach(item->System.out.printf("%s%d\n",item,index[0]++));外部迭代:以下方法适用于并行流,只要原始集合支持随机访问。Listtokens=...;IntStream.range(0,toke
在JavaScript中你可以这样做:setInterval(func,delay);我似乎无法在谷歌上找到任何我真正要找的东西。是否有ruby等价物?提前致谢。 最佳答案 你可以做类似的事情:Thread.newdoloopdosleepdelay#yourcodehereendend或者你可以定义一个函数:#@return[Thread]returnloopthreadreferencedefset_interval(delay)Thread.newdoloopdosleepdelayyield#callpassedblocke
我如何做Ruby方法"Flatten"RubyMethod在C#中。此方法将锯齿状数组展平为一维数组。例如:s=[1,2,3]#=>[1,2,3]t=[4,5,6,[7,8]]#=>[4,5,6,[7,8]]a=[s,t,9,10]#=>[[1,2,3],[4,5,6,[7,8]],9,10]a.flatten#=>[1,2,3,4,5,6,7,8,9,10 最佳答案 递归解决方案:IEnumerableFlatten(IEnumerablearray){foreach(variteminarray){if(itemisIEnume