.NET은 I/O 바인딩 및 컴퓨팅 바인딩된 비동기 작업을 수행하기 위한 다음 두 가지 표준 패턴을 제공합니다.
비동기 작업이 시작/끝 메서드 쌍으로 표현되는 APM(비동기 프로그래밍 모델)입니다. 예: FileStream.BeginRead 및 Stream.EndRead.
EAP(이벤트 기반 비동기 패턴)은 비동기 작업이
<OperationName>Async
및<OperationName>Completed
로 명명된 메서드/이벤트 쌍으로 표현되는 패턴입니다. 예: WebClient.DownloadStringAsync 및 WebClient.DownloadStringCompleted.
TPL(작업 병렬 라이브러리)은 비동기 패턴 중 하나와 함께 다양한 방법으로 사용할 수 있습니다. APM 및 EAP 작업을 모두 라이브러리 사용자가 Task
개체로 노출할 수 있으며, APM 패턴을 노출하는 대신 Task
개체를 사용하여 내부적으로 구현할 수도 있습니다. 두 시나리오 모두 개체를 사용하여 Task
코드를 간소화하고 다음과 같은 유용한 기능을 활용할 수 있습니다.
작업이 시작된 후 언제든지 작업 연속의 형태로 콜백을 등록합니다.
Begin_
및 ContinueWhenAll 메서드 또는 ContinueWhenAny 및 WaitAll 메서드를 사용하여 WaitAny 메서드에 대한 응답으로 실행되는 여러 작업을 조정합니다.동일한
Task
개체에서 비동기 I/O 바인딩 및 컴퓨팅 바인딩된 작업을 캡슐화합니다.Task
개체의 상태를 모니터링합니다."작업의 상태를
Task
을 사용하여 TaskCompletionSource<TResult> 개체로 마샬링합니다."
태스크에서 APM 연산 감싸기
System.Threading.Tasks.TaskFactory 클래스와 System.Threading.Tasks.TaskFactory<TResult> 클래스는 모두 TaskFactory.FromAsync 메서드와 TaskFactory<TResult>.FromAsync 메서드의 여러 오버로드를 제공하여, APM begin/end 메서드 쌍을 하나의 Task 또는 Task<TResult> 인스턴스로 캡슐화할 수 있게 합니다. 다양한 오버로드는 0~3개의 입력 매개 변수가 있는 모든 시작/끝 메서드 쌍을 수용합니다.
값을 반환하는 End
메서드를 가진 쌍의 경우, Visual Basic의 Function
에서 TaskFactory<TResult>를 사용하여 Task<TResult>를 생성하는 메서드를 이용하십시오. Visual Basic의 End
인 경우 void를 반환하는 메서드에 대해서는, Sub
을(를) 생성하는 TaskFactory의 메서드를 Task 사용하세요.
세 개 이상의 매개 변수가 있거나 Begin
또는 ref
매개 변수가 포함된 몇 가지 경우에는, 메서드만 캡슐화하는 추가 out
오버로드가 제공됩니다.
다음 예제는 FromAsync
오버로드가 FileStream.BeginRead 및 FileStream.EndRead 메서드와 일치하는 서명을 보여줍니다.
public Task<TResult> FromAsync<TArg1, TArg2, TArg3>(
Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod, //BeginRead
Func<IAsyncResult, TResult> endMethod, //EndRead
TArg1 arg1, // the byte[] buffer
TArg2 arg2, // the offset in arg1 at which to start writing data
TArg3 arg3, // the maximum number of bytes to read
object state // optional state information
)
Public Function FromAsync(Of TArg1, TArg2, TArg3)(
ByVal beginMethod As Func(Of TArg1, TArg2, TArg3, AsyncCallback, Object, IAsyncResult),
ByVal endMethod As Func(Of IAsyncResult, TResult),
ByVal dataBuffer As TArg1,
ByVal byteOffsetToStartAt As TArg2,
ByVal maxBytesToRead As TArg3,
ByVal stateInfo As Object)
이 오버로드는 다음과 같이 세 개의 입력 매개 변수를 사용합니다. 첫 번째 매개 변수는 메서드의 서명과 일치하는 대리자 Func<T1,T2,T3,T4,T5,TResult> 입니다FileStream.BeginRead. 두 번째 매개 변수는 Func<T,TResult>를 받아 IAsyncResult를 반환하는 TResult
대리자입니다.
EndRead이 정수를 반환하기 때문에, 컴파일러는 TResult
의 형식을 Int32로, 작업의 형식을 Task로 유추합니다. 마지막 네 개의 매개 변수는 메서드의 매개 변수와 FileStream.BeginRead 동일합니다.
파일 데이터를 저장할 버퍼입니다.
데이터 쓰기를 시작할 버퍼의 오프셋입니다.
파일에서 읽을 최대 데이터 양입니다.
콜백에 전달할 사용자 정의 상태 데이터를 저장하는 선택적 개체입니다.
콜백 기능에 ContinueWith 사용
바이트 수와 달리 파일의 데이터에 액세스해야 하는 경우 메서드로 FromAsync 는 충분하지 않습니다. 대신 Task의 Result
속성에 파일 데이터가 포함된 것을 사용합니다. 원래 작업에 연속 작업을 추가하여 이 작업을 수행할 수 있습니다. 연속 작업은 일반적으로 대리자가 AsyncCallback 수행하는 작업을 수행합니다. 선행 작업이 완료되고 데이터 버퍼가 채워지면 호출됩니다. (반환하기 전에 FileStream 개체를 닫아야 합니다.)
다음 예제에서는 Task 클래스의 BeginRead
, /, EndRead
쌍을 캡슐화하는 FileStream를 반환하는 방법을 보여 줍니다.
const int MAX_FILE_SIZE = 14000000;
public static Task<string> GetFileStringAsync(string path)
{
FileInfo fi = new FileInfo(path);
byte[] data = null;
data = new byte[fi.Length];
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, data.Length, true);
//Task<int> returns the number of bytes read
Task<int> task = Task<int>.Factory.FromAsync(
fs.BeginRead, fs.EndRead, data, 0, data.Length, null);
// It is possible to do other work here while waiting
// for the antecedent task to complete.
// ...
// Add the continuation, which returns a Task<string>.
return task.ContinueWith((antecedent) =>
{
fs.Close();
// Result = "number of bytes read" (if we need it.)
if (antecedent.Result < 100)
{
return "Data is too small to bother with.";
}
else
{
// If we did not receive the entire file, the end of the
// data buffer will contain garbage.
if (antecedent.Result < data.Length)
Array.Resize(ref data, antecedent.Result);
// Will be returned in the Result property of the Task<string>
// at some future point after the asynchronous file I/O operation completes.
return new UTF8Encoding().GetString(data);
}
});
}
Const MAX_FILE_SIZE As Integer = 14000000
Shared Function GetFileStringAsync(ByVal path As String) As Task(Of String)
Dim fi As New FileInfo(path)
Dim data(fi.Length - 1) As Byte
Dim fs As FileStream = New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, data.Length, True)
' Task(Of Integer) returns the number of bytes read
Dim myTask As Task(Of Integer) = Task(Of Integer).Factory.FromAsync(
AddressOf fs.BeginRead, AddressOf fs.EndRead, data, 0, data.Length, Nothing)
' It is possible to do other work here while waiting
' for the antecedent task to complete.
' ...
' Add the continuation, which returns a Task<string>.
Return myTask.ContinueWith(Function(antecedent)
fs.Close()
If (antecedent.Result < 100) Then
Return "Data is too small to bother with."
End If
' If we did not receive the entire file, the end of the
' data buffer will contain garbage.
If (antecedent.Result < data.Length) Then
Array.Resize(data, antecedent.Result)
End If
' Will be returned in the Result property of the Task<string>
' at some future point after the asynchronous file I/O operation completes.
Return New UTF8Encoding().GetString(data)
End Function)
End Function
그런 다음 다음과 같이 메서드를 호출할 수 있습니다.
Task<string> t = GetFileStringAsync(path);
// Do some other work:
// ...
try
{
Console.WriteLine(t.Result.Substring(0, 500));
}
catch (AggregateException ae)
{
Console.WriteLine(ae.InnerException.Message);
}
Dim myTask As Task(Of String) = GetFileStringAsync(path)
' Do some other work
' ...
Try
Console.WriteLine(myTask.Result.Substring(0, 500))
Catch ex As AggregateException
Console.WriteLine(ex.InnerException.Message)
End Try
사용자 지정 상태 데이터 제공
일반적인 IAsyncResult 작업에서 대리자에게 사용자 지정 상태 데이터가 필요한 경우 AsyncCallback 메서드의 마지막 매개 변수 Begin
를 통해 전달해야 하므로 결국 콜백 메서드에 전달되는 개체에 IAsyncResult 데이터를 패키지할 수 있습니다. 일반적으로 메서드를 FromAsync
사용할 때는 필요하지 않습니다. 사용자 지정 데이터가 계속작업에 알려진 경우 계속작업 대리자에서 직접 캡처할 수 있습니다. 다음 예제는 이전 예제와 유사하지만, 선행 작업의 Result
속성을 검사하는 대신 연속 작업에서 연속 작업의 사용자 대리자가 직접 액세스할 수 있는 사용자 지정 상태 데이터를 검사합니다.
public Task<string> GetFileStringAsync2(string path)
{
FileInfo fi = new FileInfo(path);
byte[] data = new byte[fi.Length];
MyCustomState state = GetCustomState();
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, data.Length, true);
// We still pass null for the last parameter because
// the state variable is visible to the continuation delegate.
Task<int> task = Task<int>.Factory.FromAsync(
fs.BeginRead, fs.EndRead, data, 0, data.Length, null);
return task.ContinueWith((antecedent) =>
{
// It is safe to close the filestream now.
fs.Close();
// Capture custom state data directly in the user delegate.
// No need to pass it through the FromAsync method.
if (state.StateData.Contains("New York, New York"))
{
return "Start spreading the news!";
}
else
{
// If we did not receive the entire file, the end of the
// data buffer will contain garbage.
if (antecedent.Result < data.Length)
Array.Resize(ref data, antecedent.Result);
// Will be returned in the Result property of the Task<string>
// at some future point after the asynchronous file I/O operation completes.
return new UTF8Encoding().GetString(data);
}
});
}
Public Function GetFileStringAsync2(ByVal path As String) As Task(Of String)
Dim fi = New FileInfo(path)
Dim data(fi.Length - 1) As Byte
Dim state As New MyCustomState()
Dim fs As New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, data.Length, True)
' We still pass null for the last parameter because
' the state variable is visible to the continuation delegate.
Dim myTask As Task(Of Integer) = Task(Of Integer).Factory.FromAsync(
AddressOf fs.BeginRead, AddressOf fs.EndRead, data, 0, data.Length, Nothing)
Return myTask.ContinueWith(Function(antecedent)
fs.Close()
' Capture custom state data directly in the user delegate.
' No need to pass it through the FromAsync method.
If (state.StateData.Contains("New York, New York")) Then
Return "Start spreading the news!"
End If
' If we did not receive the entire file, the end of the
' data buffer will contain garbage.
If (antecedent.Result < data.Length) Then
Array.Resize(data, antecedent.Result)
End If
'/ Will be returned in the Result property of the Task<string>
'/ at some future point after the asynchronous file I/O operation completes.
Return New UTF8Encoding().GetString(data)
End Function)
End Function
여러 FromAsync 작업 동기화
정적 ContinueWhenAll 및 ContinueWhenAny 메서드는 FromAsync
메서드와 함께 사용할 때 유연성을 제공합니다. 다음 예제에서는 여러 비동기 I/O 작업을 시작한 다음 연속 작업을 실행하기 전에 모든 작업이 완료되기를 기다리는 방법을 보여 줍니다.
public Task<string> GetMultiFileData(string[] filesToRead)
{
FileStream fs;
Task<string>[] tasks = new Task<string>[filesToRead.Length];
byte[] fileData = null;
for (int i = 0; i < filesToRead.Length; i++)
{
fileData = new byte[0x1000];
fs = new FileStream(filesToRead[i], FileMode.Open, FileAccess.Read, FileShare.Read, fileData.Length, true);
// By adding the continuation here, the
// Result of each task will be a string.
tasks[i] = Task<int>.Factory.FromAsync(
fs.BeginRead, fs.EndRead, fileData, 0, fileData.Length, null)
.ContinueWith((antecedent) =>
{
fs.Close();
// If we did not receive the entire file, the end of the
// data buffer will contain garbage.
if (antecedent.Result < fileData.Length)
Array.Resize(ref fileData, antecedent.Result);
// Will be returned in the Result property of the Task<string>
// at some future point after the asynchronous file I/O operation completes.
return new UTF8Encoding().GetString(fileData);
});
}
// Wait for all tasks to complete.
return Task<string>.Factory.ContinueWhenAll(tasks, (data) =>
{
// Propagate all exceptions and mark all faulted tasks as observed.
Task.WaitAll(data);
// Combine the results from all tasks.
StringBuilder sb = new StringBuilder();
foreach (var t in data)
{
sb.Append(t.Result);
}
// Final result to be returned eventually on the calling thread.
return sb.ToString();
});
}
Public Function GetMultiFileData(ByVal filesToRead As String()) As Task(Of String)
Dim fs As FileStream
Dim tasks(filesToRead.Length - 1) As Task(Of String)
Dim fileData() As Byte = Nothing
For i As Integer = 0 To filesToRead.Length
fileData(&H1000) = New Byte()
fs = New FileStream(filesToRead(i), FileMode.Open, FileAccess.Read, FileShare.Read, fileData.Length, True)
' By adding the continuation here, the
' Result of each task will be a string.
tasks(i) = Task(Of Integer).Factory.FromAsync(AddressOf fs.BeginRead,
AddressOf fs.EndRead,
fileData,
0,
fileData.Length,
Nothing).
ContinueWith(Function(antecedent)
fs.Close()
'If we did not receive the entire file, the end of the
' data buffer will contain garbage.
If (antecedent.Result < fileData.Length) Then
ReDim Preserve fileData(antecedent.Result)
End If
'Will be returned in the Result property of the Task<string>
' at some future point after the asynchronous file I/O operation completes.
Return New UTF8Encoding().GetString(fileData)
End Function)
Next
Return Task(Of String).Factory.ContinueWhenAll(tasks, Function(data)
' Propagate all exceptions and mark all faulted tasks as observed.
Task.WaitAll(data)
' Combine the results from all tasks.
Dim sb As New StringBuilder()
For Each t As Task(Of String) In data
sb.Append(t.Result)
Next
' Final result to be returned eventually on the calling thread.
Return sb.ToString()
End Function)
End Function
End 메서드에 대해서만 FromAsync 작업
입력 매개변수가 세 개 이상이거나 Begin
, ref
매개변수가 있는 경우에는 out
오버로드, 예를 들어 FromAsync
,을 사용하여 TaskFactory<TResult>.FromAsync(IAsyncResult, Func<IAsyncResult,TResult>) 메서드를 전용으로 나타낼 수 있습니다. 이러한 메서드는 IAsyncResult가 주어지고 이를 Task에 캡슐화하려는 모든 시나리오에서도 사용할 수 있습니다.
static Task<String> ReturnTaskFromAsyncResult()
{
IAsyncResult ar = DoSomethingAsynchronously();
Task<String> t = Task<string>.Factory.FromAsync(ar, _ =>
{
return (string)ar.AsyncState;
});
return t;
}
Shared Function ReturnTaskFromAsyncResult() As Task(Of String)
Dim ar As IAsyncResult = DoSomethingAsynchronously()
Dim t As Task(Of String) = Task(Of String).Factory.FromAsync(ar, Function(res) CStr(res.AsyncState))
Return t
End Function
FromAsync 작업 시작 및 취소
메서드에서 반환된 FromAsync
작업의 상태가 WaitingForActivation
있으며 작업이 만들어진 후 특정 시점에 시스템에서 시작됩니다. 이러한 작업에서 Start를 호출하려고 하면 예외가 발생합니다.
기본 .NET API FromAsync
는 현재 파일 또는 네트워크 I/O의 진행 중인 취소를 지원하지 않으므로 작업을 취소할 수 없습니다. 호출을 캡슐화하는 FromAsync
메서드에 취소 기능을 추가할 수 있지만 호출되기 전 FromAsync
이나 완료된 후에만 취소에 응답할 수 있습니다(예: 연속 작업).
예를 들어 WebClientEAP를 지원하는 일부 클래스는 취소를 지원하며 취소 토큰을 사용하여 해당 네이티브 취소 기능을 통합할 수 있습니다.
복잡한 EAP 작업을 작업으로 제시하다
TPL은 FromAsync
패턴을 래핑하는 메서드 패밀리와 동일한 방식으로 IAsyncResult 이벤트 기반 비동기 작업을 캡슐화하도록 특별히 설계된 메서드를 제공하지 않습니다. 그러나 TPL은 임의의 작업 집합을 System.Threading.Tasks.TaskCompletionSource<TResult>로 표현할 수 있는 Task<TResult> 클래스를 제공합니다. 작업은 동기 또는 비동기일 수 있으며 I/O 바인딩 또는 컴퓨팅 바인딩 또는 둘 다일 수 있습니다.
다음 예제에서는 TaskCompletionSource<TResult>를 사용하여 비동기 WebClient 작업 집합을 기본 Task<TResult>로 클라이언트 코드에 노출하는 방법을 보여 줍니다. 이 메서드를 사용하면 검색할 웹 URL 배열과 검색할 용어 또는 이름을 입력한 다음 각 사이트에서 검색 용어가 발생하는 횟수를 반환할 수 있습니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
public class SimpleWebExample
{
public Task<string[]> GetWordCountsSimplified(string[] urls, string name,
CancellationToken token)
{
TaskCompletionSource<string[]> tcs = new TaskCompletionSource<string[]>();
WebClient[] webClients = new WebClient[urls.Length];
object m_lock = new object();
int count = 0;
List<string> results = new List<string>();
// If the user cancels the CancellationToken, then we can use the
// WebClient's ability to cancel its own async operations.
token.Register(() =>
{
foreach (var wc in webClients)
{
if (wc != null)
wc.CancelAsync();
}
});
for (int i = 0; i < urls.Length; i++)
{
webClients[i] = new WebClient();
#region callback
// Specify the callback for the DownloadStringCompleted
// event that will be raised by this WebClient instance.
webClients[i].DownloadStringCompleted += (obj, args) =>
{
// Argument validation and exception handling omitted for brevity.
// Split the string into an array of words,
// then count the number of elements that match
// the search term.
string[] words = args.Result.Split(' ');
string NAME = name.ToUpper();
int nameCount = (from word in words.AsParallel()
where word.ToUpper().Contains(NAME)
select word)
.Count();
// Associate the results with the url, and add new string to the array that
// the underlying Task object will return in its Result property.
lock (m_lock)
{
results.Add(String.Format("{0} has {1} instances of {2}", args.UserState, nameCount, name));
// If this is the last async operation to complete,
// then set the Result property on the underlying Task.
count++;
if (count == urls.Length)
{
tcs.TrySetResult(results.ToArray());
}
}
};
#endregion
// Call DownloadStringAsync for each URL.
Uri address = null;
address = new Uri(urls[i]);
webClients[i].DownloadStringAsync(address, address);
} // end for
// Return the underlying Task. The client code
// waits on the Result property, and handles exceptions
// in the try-catch block there.
return tcs.Task;
}
}
Imports System.Collections.Generic
Imports System.Net
Imports System.Threading
Imports System.Threading.Tasks
Public Class SimpleWebExample
Dim tcs As New TaskCompletionSource(Of String())
Dim token As CancellationToken
Dim results As New List(Of String)
Dim m_lock As New Object()
Dim count As Integer
Dim addresses() As String
Dim nameToSearch As String
Public Function GetWordCountsSimplified(ByVal urls() As String, ByVal str As String,
ByVal token As CancellationToken) As Task(Of String())
addresses = urls
nameToSearch = str
Dim webClients(urls.Length - 1) As WebClient
' If the user cancels the CancellationToken, then we can use the
' WebClient's ability to cancel its own async operations.
token.Register(Sub()
For Each wc As WebClient In webClients
If wc IsNot Nothing Then
wc.CancelAsync()
End If
Next
End Sub)
For i As Integer = 0 To urls.Length - 1
webClients(i) = New WebClient()
' Specify the callback for the DownloadStringCompleted
' event that will be raised by this WebClient instance.
AddHandler webClients(i).DownloadStringCompleted, AddressOf WebEventHandler
Dim address As New Uri(urls(i))
' Pass the address, and also use it for the userToken
' to identify the page when the delegate is invoked.
webClients(i).DownloadStringAsync(address, address)
Next
' Return the underlying Task. The client code
' waits on the Result property, and handles exceptions
' in the try-catch block there.
Return tcs.Task
End Function
Public Sub WebEventHandler(ByVal sender As Object, ByVal args As DownloadStringCompletedEventArgs)
If args.Cancelled = True Then
tcs.TrySetCanceled()
Return
ElseIf args.Error IsNot Nothing Then
tcs.TrySetException(args.Error)
Return
Else
' Split the string into an array of words,
' then count the number of elements that match
' the search term.
Dim words() As String = args.Result.Split(" "c)
Dim name As String = nameToSearch.ToUpper()
Dim nameCount = (From word In words.AsParallel()
Where word.ToUpper().Contains(name)
Select word).Count()
' Associate the results with the url, and add new string to the array that
' the underlying Task object will return in its Result property.
SyncLock (m_lock)
results.Add(String.Format("{0} has {1} instances of {2}", args.UserState, nameCount, nameToSearch))
count = count + 1
If (count = addresses.Length) Then
tcs.TrySetResult(results.ToArray())
End If
End SyncLock
End If
End Sub
End Class
추가 예외 처리를 포함하고 클라이언트 코드에서 메서드를 호출하는 방법을 보여주는 보다 완전한 예제는 방법: 태스크에서 EAP 패턴 래핑을 참조하세요.
어느 작업이든 TaskCompletionSource<TResult>에 의해 만들어지면, 해당 TaskCompletionSource
에 의해 시작되므로 사용자 코드에서는 해당 작업의 Start
메서드를 호출하지 않도록 해야 합니다.
작업을 사용하여 APM 패턴 구현
일부 시나리오에서는 API에서 begin/end 메서드 쌍을 사용하여 패턴을 직접 드러내는 것이 IAsyncResult 바람직할 수 있습니다. 예를 들어 기존 API와의 일관성을 유지하거나 이 패턴이 필요한 자동화된 도구가 있을 수 있습니다. 이러한 경우 개체를 사용하여 Task
APM 패턴이 내부적으로 구현되는 방식을 간소화할 수 있습니다.
다음 예제에서는 작업을 사용하여 장기 실행 컴퓨팅 바인딩된 메서드에 대한 APM begin/end 메서드 쌍을 구현하는 방법을 보여 줍니다.
class Calculator
{
public IAsyncResult BeginCalculate(int decimalPlaces, AsyncCallback ac, object state)
{
Console.WriteLine($"Calling BeginCalculate on thread {Thread.CurrentThread.ManagedThreadId}");
Task<string> f = Task<string>.Factory.StartNew(_ => Compute(decimalPlaces), state);
if (ac != null) f.ContinueWith((res) => ac(f));
return f;
}
public string Compute(int numPlaces)
{
Console.WriteLine($"Calling compute on thread {Thread.CurrentThread.ManagedThreadId}");
// Simulating some heavy work.
Thread.SpinWait(500000000);
// Actual implementation left as exercise for the reader.
// Several examples are available on the Web.
return "3.14159265358979323846264338327950288";
}
public string EndCalculate(IAsyncResult ar)
{
Console.WriteLine($"Calling EndCalculate on thread {Thread.CurrentThread.ManagedThreadId}");
return ((Task<string>)ar).Result;
}
}
public class CalculatorClient
{
static int decimalPlaces = 12;
public static void Main()
{
Calculator calc = new Calculator();
int places = 35;
AsyncCallback callBack = new AsyncCallback(PrintResult);
IAsyncResult ar = calc.BeginCalculate(places, callBack, calc);
// Do some work on this thread while the calculator is busy.
Console.WriteLine("Working...");
Thread.SpinWait(500000);
Console.ReadLine();
}
public static void PrintResult(IAsyncResult result)
{
Calculator c = (Calculator)result.AsyncState;
string piString = c.EndCalculate(result);
Console.WriteLine($"Calling PrintResult on thread {Thread.CurrentThread.ManagedThreadId}; result = {piString}");
}
}
Class Calculator
Public Function BeginCalculate(ByVal decimalPlaces As Integer, ByVal ac As AsyncCallback, ByVal state As Object) As IAsyncResult
Console.WriteLine("Calling BeginCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId)
Dim myTask = Task(Of String).Factory.StartNew(Function(obj) Compute(decimalPlaces), state)
myTask.ContinueWith(Sub(antecedent) ac(myTask))
End Function
Private Function Compute(ByVal decimalPlaces As Integer)
Console.WriteLine("Calling compute on thread {0}", Thread.CurrentThread.ManagedThreadId)
' Simulating some heavy work.
Thread.SpinWait(500000000)
' Actual implementation left as exercise for the reader.
' Several examples are available on the Web.
Return "3.14159265358979323846264338327950288"
End Function
Public Function EndCalculate(ByVal ar As IAsyncResult) As String
Console.WriteLine("Calling EndCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId)
Return CType(ar, Task(Of String)).Result
End Function
End Class
Class CalculatorClient
Shared decimalPlaces As Integer
Shared Sub Main()
Dim calc As New Calculator
Dim places As Integer = 35
Dim callback As New AsyncCallback(AddressOf PrintResult)
Dim ar As IAsyncResult = calc.BeginCalculate(places, callback, calc)
' Do some work on this thread while the calculator is busy.
Console.WriteLine("Working...")
Thread.SpinWait(500000)
Console.ReadLine()
End Sub
Public Shared Sub PrintResult(ByVal result As IAsyncResult)
Dim c As Calculator = CType(result.AsyncState, Calculator)
Dim piString As String = c.EndCalculate(result)
Console.WriteLine("Calling PrintResult on thread {0}; result = {1}",
Thread.CurrentThread.ManagedThreadId, piString)
End Sub
End Class
StreamExtensions 샘플 코드 사용
.NET Standard 병렬 확장 추가 리포지토리의 StreamExtensions.cs 파일에는 비동기 파일 및 네트워크 I/O에 개체를 사용하는 Task
몇 가지 참조 구현이 포함되어 있습니다.
참고하십시오
.NET