C# How do I pass object back to main thread from worker thread?
How do I handle data returned from a worker thread public 开发者_如何学编程method?
Thanks.
If the worker thread is a Task<TResult>
, then you can retrieve the result from the Task<TResult>.Result
property.
If the worker thread is a BackgroundWorker
, then you can retrieve the result from the
RunWorkerCompletedEventArgs.Result
property in the argument object passed to BackgroundWorker.RunWorkerCompleted
.
If the worker thread is a ThreadPool
thread executed via Delegate.BeginInvoke
, then you can retrieve the result by calling EndInvoke
, even if the delegate has already completed.
If the worker thread is a Thread
, or a ThreadPool
thread executed via ThreadPool.QueueUserWorkItem
, then you must "return" the result by setting a subobject of a parameter, by using a lambda-bound variable, or by using a global variable.
It depends how the thread was created and what kind of thread the main thread is. If it's a WinForms or WPF thread the most straight forward way is to use the SynchronizationContext
of the main thread to perform an operation back on the main thread once the worker thread is completed.
void StartWorker() {
var context = SynchronizationContext.Current;
ThreadPool.QueueUserWorkItem(WorkerThread, context);
}
void WorkerThread(object state) {
var context = (SynchronizationContext)state;
...;
context.Post(WorkerDone, ...);
}
void WorkerDone(object state) {
// back on UI thread
}
It depends.
What is the main thread?
What is it doing with the data?
In WinForms, for example, you can call the Invoke
method to run a callback on the main thread with the data as a parameter.
精彩评论