等待在函数中触发事件

时间:2017-01-19 16:10:29

标签: c# .net events

我有以下活动&功能:

x = 1
With Workbooks.Open(fileName:=FilesToOpen(x))
    TextFileName = Sheets(1).Name
    .Worksheets(1).Columns("A:A").TextToColumns _
        Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
        Tab:=False, Semicolon:=False, Comma:=False, Space:=False, _
        Other:=True, OtherChar:="|"
    lastCol = Sheets(TextFileName).Range("a1").End(xlToRight).Column
    lastRow = Sheets(TextFileName).Cells(65536, lastCol).End(xlUp).Row
    Selection.Copy
    .Close False

'clear the contents of the sheets, copy the data into the sheet with same >     name as text file

With ThisWorkbook.Worksheets(TextFileName)
    lastCol = Sheets(TextFileName).Range("a1").End(xlToRight).Column
    lastRow = Sheets(TextFileName).Cells(65536, lastCol).End(xlUp).Row
    Sheets(TextFileName).Range("a1", ActiveSheet.Cells(lastRow, lastCol)).Select
    Selection.ClearContents
    Sheets(TextFileName).Range("A1").PasteSpecial
End With

我的目标是阻止函数,直到事件被触发。

2 个答案:

答案 0 :(得分:-1)

您可以使用AutoResetEvent:

static void rViewer_DocumentLoaded(object sender, EventArgs e)
{
    are.Set();
    //Do something
}

static RadPdfViewer rViewer = new RadPdfViewer();
static RadPrintDocument rpd = new RadPrintDocument();
static AutoResetEvent are = new AutoResetEvent(false);
internal static bool PrintReportBlocking(string sFileName, REPORT_TYPE reportType)
{
    try
    {

        rpd = new RadPrintDocument();
        rViewer = new RadPdfViewer();
        rViewer.DocumentLoaded += rViewer_DocumentLoaded;
        rViewer.LoadDocument(sFileName);
        are.WaitOne();
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

答案 1 :(得分:-1)

您可以使用TaskCompletionSource来实现此目的:

static RadPdfViewer rViewer = new RadPdfViewer();
static RadPrintDocument rpd = new RadPrintDocument();

internal static bool PrintReportBlocking(string sFileName, REPORT_TYPE reportType)      
{
    var tcs = new TaskCompletionSource<object>();
    try
    {
        rpd = new RadPrintDocument();
        rViewer = new RadPdfViewer();
        rViewer.DocumentLoaded += () => tcs.SetResult(null);
        rViewer.LoadDocument(sFileName);

        // If you really want to block, but you should probably use async/await
        tcs.Task.Wait();

        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}