使用任务可以做这样的事情:
public async Task SomeMethod()
{
// [A] Here I am in the caller thread
await OtherMethod().ConfigureAwait( false );
// [B] Here I am in some other thread
}
private async Task OtherMethod()
{
// Something here
}
在点 [A] 和 [B] 中,您可以处于不同的线程中。是否有可能通过选择线程来做类似的事情而不使用 async 和 await 关键字,它会切换到?像这样:
public void SomeMethod()
{
// [A] Here I am in the caller thread
ChangeThread();
// [B] Here I am in some other thread
}
private void ChangeThread()
{
Thread thread = new Thread(???);
// ???
}
我知道这对于委托(delegate)是可能的,但是是否可以在方法内部切换线程,并可能在方法结束时将当前线程改回原来的线程?如果没有,是否可以使用 async/await 制作一些可以更改线程的东西,但我可以控制它将切换到哪个线程(比如使用 Control.Invoke 的 UI 线程)?
最佳答案
在需要更改执行上下文然后返回到原始上下文的情况下,我总是做的是:
public async void RunWorkerAsync()
{
var result = await RetriveDataAsync();
}
public Task<Object<TItem>> RetriveResultsAsync()
{
var tokenSource = new CancellationTokenSource();
var ct = tokenSource.Token;
var source = new TaskCompletionSource<Object<TItem>>();
var task = Task.Run(() =>
{
// [B] Here I am in some other thread
while (!ConditionToStop)
{
if (ct.IsCancellationRequested)
{
tokenSource.Cancel();
ct.ThrowIfCancellationRequested();
}
}
}, ct).ContinueWith(taskCont =>
{
if (resultedData != null)
{
source.SetResult(resultedData);
}
}, ct);
bool taskCompleted = task.Wait(2000, ct);
if (!taskCompleted)
{
tokenSource.Cancel();
}
return source.Task;
}
如果您想在一个任务中执行所有操作而没有结果,只需传递数据并删除 taskCompleted 部分,并仅依赖条件停止。所有您的代码将在另一个线程上运行,并且在完成执行后将返回到您的调用线程。如果您需要的是简单且没有返回的东西,请使用
Task.Run(Action() => ExecuteSomething);
在方法中。
关于c# - 改变当前方法的执行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36694484/