Hello, dear.

I want to do this:

I have a code. It is a call to the external library and a callback from it.

I want - for further work - to make of this task.

(in particular, to use the .ContinueWith () method later).

Here is the code I want to wrap in a task:

public partial class Form1 : Form { public Form15() { InitializeComponent(); button1.Click += button1_Click; } void button1_Click(object sender, EventArgs e) { SevenZipExtractor.SetLibraryPath(@"c:\Program Files\7-Zip\7z.dll"); SevenZipCompressor compressor = new SevenZipCompressor(); compressor.ArchiveFormat=OutArchiveFormat.SevenZip; compressor.CompressionLevel=CompressionLevel.Ultra; compressor.CompressionMode=CompressionMode.Create; string[] ffNames = new[] {@"c:\Temp\my.log"}; compressor.CompressionFinished += compressor_CompressionFinished; compressor.CompressFiles(@"c:\Temp\my.log.7z", ffNames); } void compressor_CompressionFinished(object sender, EventArgs e) { MessageBox.Show("Ready!"); } } 

That is, in the row

 compressor.CompressFiles(@"c:\Temp\my.log.7z", ffNames); 

the external component starts up, in the string

 MessageBox.Show("Ready!"); 

just come callback, by which you can complete the task

(of course, it shouldn't show the messageBox - just end with the arrival of a callback)

Thanks for the tips!

    1 answer 1

    This is described in the documentation . You need to use TaskCompletionSource .

    For your case:

     async Task CompressFilesAsync( SevenZipCompressor compressor, string archiveName, params string[] fileFullNames) { var tcs = new TaskCompletionSource<int>(); // тип параметра неважен EventHandler<EventArgs> handler = null; handler = (sender, args) => { compressor.CompressionFinished -= handler; tcs.TrySetResult(0); }; compressor.CompressionFinished += handler; // кажется, это асинхронный метод, в отличие от синхронного CompressFiles compressor.BeginCompressFiles(archiveName, DispatcherPriority.Normal, fileFullNames); return tcs.Task; } 

    You can also make an extension-method from this:

     public static class SevenZipCompressorExtensions { public static async Task CompressFilesAsync( this SevenZipCompressor compressor, string archiveName, params string[] fileFullNames) { // ... } } 

    and enjoy:

     SevenZipCompressor compressor = new SevenZipCompressor() { ArchiveFormat = OutArchiveFormat.SevenZip, CompressionLevel = CompressionLevel.Ultra, CompressionMode = CompressionMode.Create }; string[] ffNames = new[] { @"c:\Temp\my.log" }; await compressor.CompressFilesAsync(@"c:\Temp\my.log.7z", ffNames); MessageBox.Show("Ready!");