[英]Change execution thread of the current method
使用任務可以執行以下操作:
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(???);
// ???
}
我知道委托可以做到這一點,但是可以在方法內部切換線程,方法結束時可以改變當前線程嗎? 如果沒有,是否有可能使用異步/等待來更改線程,但是我可以控制將切換到哪個線程(例如使用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即可停止。 所有您的代碼將在另一個線程上運行,並在完成后執行將返回到您的調用線程。 如果簡單的東西沒有回報,那么您只需要使用
Task.Run(Action() => ExecuteSomething);
在方法內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.