c# - Mark task as completed -
i’m implementing client protocol myprotocol on tcp/ip. protocol’s connect() method should have signature similar of tcpclient.connectasync() – is, should return task:
task myprotocol.connect (…);
this method (myprotocol.connect()
) should make asynchronous tcp/ip connection (via tcpclient.connectasync()
), return non-completed task t , periodically send message m server – again asynchronously (via networkstream.writeasync()
). when response r received server – again asynchronously (via networkstream.readasync()
), myprotocol.connect()
should complete task t. i’m doing following:
// client of protocol: var task = myprotocol.connect(); // asynchronous call, don’t want wait until connected task.continuewith(t => { // connected – doing onconnected stuff … }); // myprotocol.connect() implementation: public class myprotocol { private task connecttask; public task connect(…) { var tcpipconnecttask = mtcpipprotocol.connect(…); tcpipconnecttask.continuewith(t => { connecttask = new task(); } return connecttask; } }
periodical sending of message m server has done through timer. once response r received server asynchronously, connecttask
must marked completed, , don’t see ways of doing that. well, strictly speaking, have managed mark connecttask
completed; i’m wrapping in taskcompletionsource<bool>
, use taskcompletionsource.setresult(true)
. i’m wondering if only, let alone best way of accomplishing need? don’t fact taskcompletionsource<>
has have non-void task result type (i used bool), i.e. there’s no non-generic version.
until tpl arrived, had our own similar framework , method task.notifycompleted()
, create task in 1 place, , mark completed in place – working asynchronously. i’ve read tasks in tpl seems imply task completes if delegate runs last line… or missing simple?
since you're using .net 4.5, should use c# 5.0 async
-await
, meant kind of situations. code (somewhat pseudo-codish):
public task connectasync() { await clientconnectasync(); while (true) { await sendmessageasync(); var response = await receivemessageasync(); if (response == r) return; await task.delay(period); } }
to answer questions:
however i’m wondering if only, let alone best way of accomplishing need?
if don't want use async
-await
, yes, taskcompletionsource
general-purpose way of doing this.
i don’t fact
taskcompletionsource<>
has have non-void task result type (i used bool), i.e. there’s no non-generic version.
that annoying, doesn't matter, since task<t>
inherits task
.
but i’ve read tasks in tpl seems imply task completes if delegate runs last line […]
that's true task
s have delegate run (those can created using task.run()
, task.factory.startnew()
or new task()
). doesn't apply task
s no delegate, can created using async
-await
or taskcompletionsource
.
Comments
Post a Comment