1

我有一个 WCF 服务,它提供了一种创建文件的方法。有时这个文件需要一点时间才能出现,如果之后立即调用其他依赖于该文件存在的方法,它们就会失败。因此,我想在继续之前检查文件是否已出现。

在我的客户端类中,我可以调用服务方法,然后循环直到文件出现,然后再继续 - 这非常有效。但是如果我循环直到文件出现在服务方法中,它永远不会发现文件已经创建 -除非我在检查之前调用 MessageBox.Show() 。如果我这样做了,它几乎会立即找到它,就像我从客户那里调用它一样。

该文件在服务方法正在寻找它的时候肯定存在(编辑:不使用 File.Exists() 正如我之前写的那样) - 那么为什么找不到它呢?为什么 MessageBox.Show() 解决了这个问题?

我假设它一定是一个我不明白的线程问题,因为它在服务外部工作,并且如果你调用 MessageBox.Show() (这会阻塞 UI 线程?),但我有点损失,所以任何帮助将不胜感激。

更多信息:如果这与线程问题相关,该服务由正在运行的 GUI 应用程序作为插件托管。感谢大家。

编辑:这是代码的一个版本。我最初没有发布这个,因为它使用了第三方库,所以我不确定它有多大帮助:

// The WCF service, in which HasCompiled(name) never
// returns true unless MessageBox.Show() is called:
public void CompileScript(string name)
{               
   // CompileFile outputs a file to disk:
   string debug = NWN2Toolset.NWN2ToolsetMainForm.Compiler.CompileFile(script.Name,GetModuleTempPath());    
   if (debug.Length > 0)
      throw new InvalidDataException("'" + name + "' could not be compiled: " + debug);

   // If the following line is commented out, this method never returns:
   MessageBox.Show("blabla");

   while (!HasCompiled(name));
}

public bool HasCompiled(string name)
{
    NWN2GameModule module = GetModule();
    OEIResRef cResRef = new OEIResRef(name);    
    IResourceEntry entry = module.Repository.FindResource(cResRef,resourceType);
    return entry != null;
}

// The client class, in which HasCompiled(name) returns true almost immediately:
[Test]
public void TestCompilesScript()
{
    service.AddScript(name,scriptContents);
    service.CompileScript(name);

    while (!service.HasCompiled(name)) {
       Console.WriteLine("HasCompiled(" + name+ ") == false.");
    }
    Console.WriteLine("HasCompiled(" + name+ ") == true.");
}
4

2 回答 2

0

我没有看到您的代码,因此我可以提出以下建议:要么在创建文件之前不要返回第一个方法(您可能需要更改 WCF 的默认超时)或者 - 只有第一次调用服务返回后 -循环访问服务以查看文件是否存在。

没有看到您的代码,我只能猜测 - 如果您正在使用线程, messagenox.show 会按特定顺序进行调用(因为系统会等待您关闭消息框)。

于 2009-11-17T14:26:52.563 回答
0

您可以实现回调,而不是在客户端中循环。有很多很好的例子 - http://www.google.com/search?q=wcf+callback+example

于 2009-12-25T06:36:04.120 回答