更改当前方法的执行线程
本文关键字:执行 线程 方法 | 更新日期: 2024-09-27 02:36:40
使用任务可以执行以下操作:
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]中,您可以处于不同的线程中。有没有可能用ous async做类似的事情,并在选择线程时等待关键字,它将切换到?像这样:
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(???);
// ???
}
我知道委托可以做到这一点,但是否可以在方法内部切换线程,并可能在方法结束时将当前线程改回?如果没有,是否可以使用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部分,然后只依赖Condition来停止。Al您的代码将在另一个线程上运行,在in完成后,执行将返回到您的调用线程。如果你需要的是没有回报的简单东西,只需使用
Task.Run(Action() => ExecuteSomething);
在方法中。