I am working with TPL and need to have a long running TPL task send results to the parent UI thread without terminating. I have tried several approaches and have been googling quite a bit. Does anyone know how to make this happen with TPL?
Share
You could pass in a delegate to call with periodic results, and a
SynchronizationContextwhich the task could use to invoke the callback on the correct thread. That’s basically the way thatBackgroundWorkerdoes it (and the way that the async feature of C# 5 will “know” where to call you back) – it capturesSynchronizationContext.Currenton the calling thread, then callsPost(IIRC) to post a message to the right context. You then just need to wrap the original callback in aSendOrPostCallbackwhich executes it when it’s got to the right thread.EDIT: Sample program: