C\#의 비동기 프로 그래 밍:await 와 async
5712 단어 C#비동기 프로 그래 밍병렬 프로 그래 밍입문 학습
GetSomeThing
함수 입 니 다.GetSomeThing
함 수 를 포장 해 야 합 니 다.이 함수 의 반환 값 은 Task 형식 입 니 다.이 유형 은 병렬 연산 을 하 는 작업 참조 입 니 다.이 예제ConsumeManyTime
함수 입 니 다.TestOne()
함수 중의 코드 를 참고 하 세 요.사실은 두 번 째 단계 의 함수ConsumeManyTime()
를 직접 호출 하 는 것 입 니 다.요약:비동기 프로 그래 밍 은 예제 3 단계 이지 만 사실은 두 단계 의 일이 다.첫 번 째 단 계 는 아 날로 그 응용 이 고 비동기 프로 그래 밍 자체 와 관계 가 없다.두 번 째 단 계 는 Task 반환 유형
async
의 수식 방법 을 포장 하고 이 방법 은 실제 응용 함 수 를 호출 하 며 세 번 째 단 계 는 두 번 째 단계 의 방법 을 호출 하여 아 날로 그 응용 에 대한 비동기 집행 을 실시한다.추가:비동기 프로 그래 밍 을 제외 하고 C\#는 동시 프로 그래 밍 과 관련 된 기능 을 제공 하여 동시 작업 의 개발 을 크게 간소화 하여 개발 자 들 이 스 레 드 탱크 를 만 들 거나 스 레 드 를 관리 하지 않 아 도 동시 개발 이 가 져 온 장점 을 직접 사용 할 수 있 습 니 다.예시 코드 참조
Testpallral()
.코드 는 다음 과 같다.
class Program
{
static int i = 0;
// IO
public static bool GetSomeThing(string a)
{
Thread.Sleep((new Random()).Next()%10*1000);
i++;
Console.WriteLine(DateTime.Now.ToLongTimeString()+"5-" + Thread.GetCurrentProcessorId().ToString());
return true;
}
// task , GetSomeThing
public static Task GetSomeThingAsync(string a)
{
return Task.Run(()=> { return GetSomeThing(a); }
);
}
// 1: , async , await。 await , , await ,
public async static void ConsumeManyTime()
{
Console.WriteLine(DateTime.Now.ToLongTimeString() + "3-" +Thread.GetCurrentProcessorId().ToString());
bool result = await GetSomeThingAsync("test");
Console.WriteLine(DateTime.Now.ToLongTimeString() + "4-" +Thread.GetCurrentProcessorId().ToString());
}
// 2: , , 。
public static void ContinueTaskWithConsumeManyTime()
{
Task t1 = GetSomeThingAsync("test");
t1.ContinueWith(t => { Console.WriteLine("after await finished " + t.Result + " " + Thread.GetCurrentProcessorId().ToString() + " " + i.ToString()); });
}
// 3:
public static async void TaskWhenConsumeManyTime()
{
Task t1 = GetSomeThingAsync("test");
Task t2 = GetSomeThingAsync("test");
await Task.WhenAll(t1, t2);
Console.WriteLine(DateTime.Now.ToLongTimeString() + "6-" + Thread.GetCurrentProcessorId().ToString());
}
//async await
public static void TestOne()
{
Console.WriteLine(DateTime.Now.ToLongTimeString() + "1-" + Thread.GetCurrentProcessorId().ToString());
ConsumeManyTime();
ConsumeManyTime();
Console.WriteLine(DateTime.Now.ToLongTimeString() + "2-" + Thread.GetCurrentProcessorId().ToString());
Console.WriteLine(" ");
while (Console.ReadLine() != "stop")
{
Console.WriteLine(" ");
}
}
public static void TestWithContinue()
{
Console.WriteLine(DateTime.Now.ToLongTimeString() + "1-" + Thread.GetCurrentProcessorId().ToString());
ContinueTaskWithConsumeManyTime();
ContinueTaskWithConsumeManyTime();
Console.WriteLine(DateTime.Now.ToLongTimeString() + "2-" + Thread.GetCurrentProcessorId().ToString());
Console.WriteLine(" ");
while (Console.ReadLine() != "stop")
{
Console.WriteLine(" ");
}
}
public static void TestWhen()
{
Console.WriteLine(DateTime.Now.ToLongTimeString() + "1-" + Thread.GetCurrentProcessorId().ToString());
TaskWhenConsumeManyTime();
Console.WriteLine(DateTime.Now.ToLongTimeString() + "2-" + Thread.GetCurrentProcessorId().ToString());
Console.WriteLine(" ");
while (Console.ReadLine() != "stop")
{
Console.WriteLine(" ");
}
}
public static void Testpallral()
{
ParallelLoopResult result =
Parallel.For(0, 100, async (int i) =>
{
Console.WriteLine(DateTime.Now.ToLongTimeString() + "{0}, task: {1}, thread: {2}", i,
Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
await Task.Delay(10);
Console.WriteLine(DateTime.Now.ToLongTimeString() + "after delay");
});
while (Console.ReadLine() != "stop")
{
Console.WriteLine(" ");
}
}
public static void Testpallral2()
{
ParallelLoopResult result =
Parallel.For(0, 100,async(int i, ParallelLoopState pls) =>
{
Console.WriteLine(DateTime.Now.ToLongTimeString() + "{0}, task: {1}, thread: {2}", i,
Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
await Task.Delay(10);
if (i > 5) pls.Break();
Console.WriteLine(DateTime.Now.ToLongTimeString() + "after delay");
}
);
while (Console.ReadLine() != "stop")
{
Console.WriteLine(" ");
}
}
static void Main(string[] args)
{
//TestWhen();
//Testpallral2();
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
WebView2를 Visual Studio 2017 Express에서 사용할 수 있을 때까지Evergreen .Net Framework SDK 4.8 VisualStudio2017에서 NuGet을 사용하기 때문에 패키지 관리 방법을 packages.config 대신 PackageReference를 사용해야...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.