gpt4 book ai didi

c# - 如何在不阻塞主线程的情况下将 Thread.Sleep 与 Task.Run 一起使用

转载 作者:太空狗 更新时间:2023-10-30 00:18:10 24 4
gpt4 key购买 nike

是否可以确保任务在主线程之外的另一个线程上运行?这样这段代码就不会阻塞调用线程?

var task = Task.Run(() =>
{
//third party code i don't have access to
Thread.Sleep(3000);
});

我知道有 Task.Delay 但我想确保该任务将在另一个线程上运行。

最佳答案

我认为有不同的方法可以完成您正在尝试的事情。但是根据您尝试做的事情,我认为您只使用 async/await 就可以了,它肯定不会阻塞您的 UI,并且允许您异步控制您的任务。

正如 MSDN 所说:

Async methods are intended to be non-blocking operations. An await expression in an async method doesn’t block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method. The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.

https://msdn.microsoft.com/en-us/library/mt674882.aspx

这是一个用法示例:

public async Task MyMethodAsync()
{
Task<int> runTask = RunOperationAsync();

int result = await longRunningTask;

Console.WriteLine(result);
}

public async Task<int> RunOperationAsync()
{
await Task.Delay(1000); //1 seconds delay
return 1;
}

这不会阻塞你的 UI

关于c# - 如何在不阻塞主线程的情况下将 Thread.Sleep 与 Task.Run 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41555427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com