簡體   English   中英

NSOperation和fwrite(Iphone)

[英]NSOperation and fwrite (Iphone)

我對此代碼有問題。基本上我想異步地從計時器函數執行fwrite。

這是我的計時器功能中的代碼塊。 (這將每隔0.2秒由計時器調用一次。

-(void)timerFunction
{

       WriteFileOperation * operation =
       [WriteFileOperation writeFileWithBuffer:pFile buffer:readblePixels length:nBytes*15];
       [_queue addOperation:operation]; // Here it is waiting to complete the fwrite
}

WrtiteFilerOperation是一個NSoperation類,它必須將傳遞的緩沖區寫入文件。 我在WriteFileOperation的“開始”方法中添加了此代碼。

- (void)start

{

    if (![NSThread isMainThread])
    {
        [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
        return;
    }


    [self willChangeValueForKey:@"isExecuting"];
    _isExecuting = YES;
    [self didChangeValueForKey:@"isExecuting"];

    NSLog(@"write bytes %d",fwrite(_buffer, 1, _nBytes, _file));
    free(_buffer);
    [self finish];
}

這里的問題是,我的timerFunction被NSOperation阻止,直到將緩沖區寫入文件為止(我的意思是直到start方法完成執行為止一直被阻止),並且性能似乎與將fwrite直接放置到timerFunction中相同。

我只想返回timerFunction,而無需等待start方法執行完成。

我在這里做錯了什么?

提前致謝

拉古

您的操作正在阻塞,因為您正在強迫該操作在主線程上運行其start方法,從而消除了使用NSOperationQueue的任何好處。 相反,我建議刪除上面看到的-start實現,並將代碼移至-main

- (void)main
{
    NSLog(@"write bytes %d",fwrite(_buffer, 1, _nBytes, _file));
    free(_buffer);
    [self finish];
}

應該在某些時候刪除NSLog以提高性能。 如果您要做的還不止這些,則可能需要將以上內容包裝在NSAutoreleasePool中。

為了防止多個線程同時寫入文件,應使用以下代碼將並發操作的最大數目設置為1:

[_queue setMaxConcurrentOperationCount:1];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM