Giriş
Açıklaması şöyle
Açıklaması şöyle
ConstructorThis is another simple and useful feature for implementing an easy-to-use producer-consumer pattern. Synchronizing between threads has never been easier when using a TaskCompletionSource object; it is an out-of-the-box implementation for triggering a follow-up action after releasing the source object.The TaskCompletionSource releases the Result task after setting the result (SetResult method) or canceling the task (simple SetCanceled or raising an exception, the SetException). Similar behavior can be achieved with EventWaitHandle, which implements the abstract class WaitHandle; however, this pattern fits more for sequence operations, such as, reading files, or fetching data from a remote source. Since we want to avoid holding our machine’s resources, triggering response is the more efficient solution.
Döndürülecek sonuç tipini belirtiriz. Şöyle yaparız.
var result = new TaskCompletionSource<int>();
SetResult metoduSonucu atamak için kullanırız.
Örnek
Örnek
Şöyle yaparız
TaskCompletionSource<FileInfo> taskCompletionSource = new TaskCompletionSource<FileInfo>();Task<FileInfo> anotherTask = taskCompletionSource.Task;Task fetchFileTask = Task.Factory.StartNew(()=>{FileInfo fileInfo = new FileInfo(Directory.GetFiles(Environment.CurrentDirectory)[0]);taskCompletionSource.SetResult(fileInfo);// Releasing the anotherTask.Result also be done by calling SetException or SetCancel//taskCompletionSource.SetException(new InvalidOperationException("..."));// Will raise a TaskCanceledException since the task was canceled.//taskCompletionSource.SetCanceled();});Task accessFileTask = Task.Factory.StartNew(() =>{// Calling the Result property is a blocking call; the thread continues after assigning// the Result object, receiving an exception, or canceling the task.FileInfo info = anotherTask.Result;Trace.WriteLine($"Received file '{info.Name}, last modified {info.LastWriteTime}'");// TODO: do something with the file});// Avoid exiting the test method before both tasks have finishedTask.WaitAll(fetchFileTask, accessFileTask);
Örnek
Async metodlar için şöyle yaparız
Şöyle yaparız
public async Task<string> GetDataAsync()
{
var tcs = new TaskCompletionSource<string>();
var s = await GetDataInternalAsync();
tcs.SetResult(s); // omitting SetException and
// cancellation for the sake of brevity
return tcs.Task;
}
Örnek
Thread için şöyle yaparız.public static Task<T> StartSTATask<T>(Func<T> func)
{
var tcs = new TaskCompletionSource<T>();
Thread thread = new Thread(() =>
{
try
{
tcs.SetResult(func());
}
catch (Exception e)
{
tcs.SetException(e);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return tcs.Task;
}
TrySetResult metoduŞöyle yaparız
taskSource.TrySetResult(true);
Hiç yorum yok:
Yorum Gönder