[英]How I can change the event as a different method in c#
我需要將事件作為不同的方法進行分離。.但是我正在使用TaskCompletionSource,不知道該怎么辦?
這是我的代碼
public Task<byte[]> Download(DocumentProfile profile)
{
var tcs = new TaskCompletionSource<byte[]>();
service.DownloadLastVersionCompleted += (sender, args) =>
{
if (args.Error != null)
tcs.TrySetResult(null);
if (args.Result != null)
tcs.TrySetResult(args.Result);
else
tcs.TrySetResult(new byte[0]);
};
service.DownloadLastVersionAsync(profile);
return tcs.Task;
}
我想這樣做
public Task<byte[]> Download(DocumentProfile profile)
{
var tcs = new TaskCompletionSource<byte[]>();
service.DownloadLastVersionCompleted+=OnDownloadCompleted;
service.DownloadLastVersionAsync(profile);
return tcs.Task;
}
private void OnDownloadCompleted(object sender, DownloadLastVersionCompletedEventArgs e)
{
.....
}
但是這里有個問題,我如何用那種不同的方法返回任務。 有時我有例外,因為由於這種事件而下載時,我在搜索時建議分開此事件。
我希望它清楚..
您在這里擁有的是捕獲的變量 ( tcs
),編譯器使用編譯器生成的capture-context類實現該變量 。 您可以手動實現同一件事(或類似的事情):
public Task<byte[]> Download(DocumentProfile profile)
{
var state = new DownloadState();
service.DownloadLastVersionCompleted += state.OnDownloadCompleted;
service.DownloadLastVersionAsync(profile);
return state.Task;
}
class DownloadState
{
private TaskCompletionSource<byte[]> tcs = new TaskCompletionSource<byte[]>();
public Task<byte[]> Task { get { return tcs.Task; } }
public void OnDownloadCompleted(
object sender, DownloadLastVersionCompletedEventArgs args)
{
if (args.Error != null)
tcs.TrySetResult(null);
if (args.Result != null)
tcs.TrySetResult(args.Result);
else
tcs.TrySetResult(new byte[0]);
}
}
忠告:我很擔心您永遠不會刪除service
中的事件訂閱; 如果重復使用/保留service
可能會產生不良后果。
請注意,有時您會在某些情況下傳遞給異步方法,在這種情況下,您可以作弊,例如:
public Task<byte[]> Download(DocumentProfile profile)
{
var tcs = new TaskCompletionSource<byte[]>();
service.DownloadLastVersionCompleted += OnDownloadCompleted;
service.DownloadLastVersionAsync(profile, state: tcs);
return tcs.Task;
}
private void OnDownloadCompleted(
object sender, DownloadLastVersionCompletedEventArgs args)
{
var tcs = (TaskCompletionSource<byte[]>)args.State;
if (args.Error != null)
tcs.TrySetResult(null);
if (args.Result != null)
tcs.TrySetResult(args.Result);
else
tcs.TrySetResult(new byte[0]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.