@@ -60,8 +60,14 @@ import Duct.Context
6060-- | Continue execution of the closure that we were executing when we migrated
6161-- to a new thread.
6262
63−resume :: Monad m => Context -> StateT Context m (Maybe a)
64−resume = runAsyncT . resumeContext
63+resume :: Monad m => Context -> m ()
64+resume ctx = do
65+ let s = runAsyncT (resumeContext ctx)
66+ _ <- runStateT s ctx
67+ return ()
68+
69+updateContextEvent :: Context -> a -> Context
70+updateContextEvent ctx evdata = ctx { event = Just $ unsafeCoerce evdata }
6571
6672------------------------------------------------------------------------------
6773-- Thread Management (creation, reaping and killing)
@@ -132,8 +138,9 @@ forkFinally1 action and_then =
132138 _ <- runInIO $ EL.try (restore action) >>= liftIO . and_then
133139 return ()
134140
135−forkIt :: (MonadBaseControl IO m, MonadIO m) => Context -> (Context -> m t) -> m ()
136−forkIt context runCtx = do
141+forkContext :: (MonadBaseControl IO m, MonadIO m)
142+ => Context -> (Context -> m ()) -> m ()
143+forkContext context runCtx = do
137144 child <- childContext context
138145 tid <- forkFinally1 (runCtx child) (beforeExit child)
139146 updatePendingThreads context tid
@@ -188,7 +195,7 @@ forkMaybe context runCtx = do
188195 waitForOneChild (childChannel context)
189196 (pendingThreads context)
190197 forkMaybe context runCtx
191− True -> forkIt context runCtx
198+ True -> forkContext context runCtx
192199
193200-- | 'StreamData' represents a task in a task stream being generated.
194201data StreamData a =
@@ -212,29 +219,22 @@ data StreamData a =
212219-- available we need a way to close the channel and wakeup all waiters so that
213220-- they can go away rather than waiting indefinitely.
214221--
215−-- | Execute the IO action and the continuation
222+-- | Execute the IO action resume the saved context
216223genAsyncEvents :: (MonadIO m, MonadBaseControl IO m) => Context -> IO (StreamData t) -> m ()
217224genAsyncEvents context rec = forkMaybe context loop
218225
219226 where
220227
221− -- Execute the IO computation and then the closure-continuation
222228 loop ctx = do
223229 streamData <- liftIO $ rec `catch`
224230 \(e :: SomeException) -> return $ SError e
225231
226− let run = runContWith streamData
232+ let ctx' = updateContextEvent ctx streamData
227233 case streamData of
228234 SMore _ -> do
229− forkMaybe ctx run
235+ forkMaybe ctx' resume
230236 loop ctx
231− _ -> run ctx
232−
233− -- resume the context with the result of the IO computation
234− runContWith dat ctx = do
235− let newCtx = ctx { event = Just $ unsafeCoerce dat }
236− _ <- runStateT (resume newCtx) newCtx
237− return ()
237+ _ -> resume ctx'
238238
239239-- | Run an IO action one or more times to generate a stream of tasks. The IO
240240-- action returns a 'StreamData'. When it returns an 'SMore' or 'SLast' a new